About GMainContext and thread

Hello, I’m working currently on https://gitlab.gnome.org/GNOME/glib/-/issues/2011 (a glib issue to extend coverage of gdbus name watching) and add a test case to have
a DBus vanished called in a different context that the one inside which the GDBusConnection has been created.

I managed that by creating a thread which run its own loop and watch a dbus name then close it (with g_dbus_connection_close_sync) .

This has for effect to be in the following code of gdbusconnection.c (https://gitlab.gnome.org/GNOME/glib/-/blob/master/gio/gdbusconnection.c#L1405)

  g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
  g_source_attach (idle_source, connection->main_context_at_construction);
  g_source_unref (idle_source);

I checked that main_context_at_construction is my default context (not the thread one which is what I want).
But when the callback is fired, g_main_context_get_thread_default() doesn’t return the same context but instead it returns my thread context.

Do you know how can this be ? Since the doc explicitly tell that g_source_attach made the source be executed in the context given.

Am I missing something or misunderstood the documentation ?

Thanks for any help you guys can bring.

PS: I opened a MR with my test case described here: https://gitlab.gnome.org/GNOME/glib/-/merge_requests/1904

1 Like

Hey, I found my mistake, I was running the main loop (belong to the main thread) in my custom thread so the source was dispatched in it even it is not current context.
Basically, I mixed up the notion of context with the notion of thread, believing there are the same things (meaning that a context is tied to a thread) but not at all. The important thing is in which thread you run the loop (wherever the loop was created).

Anyway, I think I’m close to get my test scenario working.


Yes, exactly. :+1: There should be a one-to-one correspondence between contexts and threads — each context should be associated with one thread and always run in that thread. But you still need to make sure that you only call g_main_loop_run() or g_main_context_iteration() in the right thread for the context you’re iterating.


This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.