Search code examples
cglibreference-counting

Reference counting a block of memory with GLib


I'm starting with GLib and would like to use its GObject reference counting features to track when a piece of memory shared between threads can be deallocated. My use case would be as follows:

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.
}

Is there a simple container object that holds a single pointer and calls free on it after its reference count reaches 0? I've tried using GPtrArray with a single element, but the container is not a GObject to be reference-counted. Also, I wouldn't like to declare a complete GObject boilerplate just to this use case.

I recognize that this is a simple thing to implement yourself - create a struct holding a pointer and an atomic counter - but I'd prefer an already-tested implementation if possible.


Solution

  • GByteArray for mutable data, GBytes for immutable data. Neither are GObjects, but both are reference counted.

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