Method

GObjectClosuresink

Declaration

void
g_closure_sink (
  GClosure* closure
)

Description

Takes over the initial ownership of a closure.

Each closure is initially created in a “floating” state, which means that the initial reference count is not owned by any caller.

This function checks to see if the object is still floating, and if so, unsets the floating state and decreases the reference count. If the closure is not floating, g_closure_sink() does nothing.

The reason for the existence of the floating state is to prevent cumbersome code sequences like:

closure = g_cclosure_new (cb_func, cb_data);
g_source_set_closure (source, closure);
g_closure_unref (closure); // GObject doesn't really need this

Because g_source_set_closure() (and similar functions) take ownership of the initial reference count, if it is unowned, we instead can write:

g_source_set_closure (source, g_cclosure_new (cb_func, cb_data));

Generally, this function is used together with g_closure_ref(). An example of storing a closure for later notification looks like:

static GClosure *notify_closure = NULL;
void
foo_notify_set_closure (GClosure *closure)
{
  if (notify_closure)
    g_closure_unref (notify_closure);
  notify_closure = closure;
  if (notify_closure)
    {
      g_closure_ref (notify_closure);
      g_closure_sink (notify_closure);
    }
}

Because g_closure_sink() may decrement the reference count of a closure (if it hasn’t been called on closure yet) just like g_closure_unref(), g_closure_ref() should be called prior to this function.