【发布时间】:2014-09-19 17:59:20
【问题描述】:
我从 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 后对其调用 free?我尝试过将 GPtrArray 与单个元素一起使用,但容器不是要进行引用计数的 GObject。另外,我不想仅仅为这个用例声明一个完整的 GObject 样板。
我认识到这是一件很容易自己实现的事情 - 创建一个包含指针和原子计数器的结构 - 但如果可能的话,我更喜欢已经测试过的实现。
【问题讨论】:
标签: c glib reference-counting