【问题标题】:Reference counting a block of memory with GLib使用 GLib 对内存块进行引用计数
【发布时间】: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


    【解决方案1】:

    GByteArray 用于可变数据,GBytes 用于不可变数据。两者都不是 GObject,但都是引用计数的。

    https://developer.gnome.org/glib/stable/glib-Byte-Arrays.html

    【讨论】:

    • 谢谢!它正是我所需要的,一开始却让我逃脱了。
    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多