我从GLib开始,并希望使用其GObject引用计数功能来跟踪线程之间共享的内存何时可以被释放。我的用例如下:
void sending_function() {
char *msg = create_message(); // Allocates some memory at the heap.
GObject *container = g_holds_my_pointer(msg, free);
for (int i = 0; i < num_threads; i++) {
g_object_ref(container);
sends_to_other_thread(other_thread, container);
}
}
void *other_thread(void *data) {
GObject *container = data;
char *msg = container->data;
// Do something with msg...
g_object_unref(container); // When the reference count reaches zero, frees msg.
}
是否有一个简单的容器对象,它包含一个指针,并在引用计数达到0后调用它?我尝试过将GPtrArray与单个元素一起使用,但容器不是要引用计数的GObject。另外,我不想仅仅针对这个用例声明一个完整的GObject样板。
我认识到这是一个简单的事情来实现自己 - 创建一个包含指针和原子计数器的结构 - 但是如果可能的话,我更喜欢已经测试过的实现。
答案 0 :(得分:3)
GByteArray表示可变数据,GBy表表示不可变数据。 GObjects都不是,但两者都是引用计数。
https://developer.gnome.org/glib/stable/glib-Byte-Arrays.html
答案 1 :(得分:0)
GLib的引用计数框可用于关联(隐藏)引用计数以在分配期间计划C数据结构。
可以使用g_rc_box_alloc(size_t)
或g_rc_box_new(type)
分配内存。
可以使用以下方法管理参考计数:
g_rc_box_acquire(ptr) // Increment refcount
g_rc_box_release(ptr) // Decrement refcount, free the memory if refcount became 0
https://developer.gnome.org/glib/stable/glib-Reference-counted-data.html