Search code examples
glibdbus

how to attach glib signal callbacks to certain thread context


So basically I'm coding following steps to create dbus based app. 1. g_bus_watch_name(callback for specific service to appear) 2. g_signal_connect to attach to certain signals provided by service. g_signal_connect(proxy,"xyz", G_CALLBACK(callback), NULL);

I want the "callback" to run under certain thread context.

Any hints would be highly appreciated


Solution

  • From the GDBusProxy documentation:

    A GDBusProxy instance can be used from multiple threads but note that all signals (e.g. “g-signal”, “g-properties-changed” and “notify”) are emitted in the thread-default main context of the thread where the instance was constructed.

    So ensure that the GMainContext you want the signals to be emitted in is the thread-default at the time you create the GDBusProxy. The typical pattern is to call g_main_context_push_thread_default() at the start of your thread function, then create the GDBusProxy and connect signals to it, and keep the object entirely within that thread.

    For more information about the recommended patterns for using a GMainContext, see the tutorial. In particular, it recommends having a single GMainContext per thread (that thread’s default), and not moving them around between threads. While supported, moving contexts between threads is slow (due to locking) and makes the control flow and thread safety of the rest of the code very hard to reason about.