引用GLib计数内存块
问题描述:
我以GLib开始,并希望使用其GObject引用计数功能来跟踪何时可以释放线程之间共享的一段内存。我用例是如下:引用GLib计数内存块
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样板文件。我认识到这是一个简单的事情来实现自己 - 创建一个持有指针和原子计数器的结构 - 但我更喜欢已经测试过的实现,如果可能的话。
答
GByteArray用于可变数据,GBytes用于不可变数据。 GObjects也不是,但都是参考计数。
https://developer.gnome.org/glib/stable/glib-Byte-Arrays.html
谢谢!它正是我所需要的,一开始就逃脱了我。 – 2014-09-19 18:57:21