GLib Multiple GMainContexts

Had a question regarding GMainContext.

I’m building a desktop app and would like to have 2 event loops. One running on the UI thread via GMainContext to process UI events and another running in a background thread to serially process async events.

Is it possible to have two instances of GMainContext on separate threads? If not, are there any recommendations on how to process async events serially in the background (via some sort of worker queue)?

Not sure if it’s relevant but the app I’m building is in Rust, using GTK-rs bindings.

I read the following in the docs but wasn’t sure if this means “one context per thread” or “only one context per process”:

A GMainContext can only be running in a single thread, but sources can be added to it and removed from it from other threads. All functions which operate on a GMainContext or a built-in GSource are thread-safe.
GLib – 2.0: The Main Event Loop

Really appreciate any help. Apologies if this has been answered before and I missed it.

Indeed you can, that’s what g_main_context_push_thread_default is for. Ideally in such case each thread has a default main thread set so that g_main_context_get_thread_default will work properly.

There are various example of this in the gio code, or in some libraries using it.


A particular context can run on only one thread at a time. But you can have as many as you want on as many threads as you want. Read this, it will help. We need that documentation to be featured more prominently. That’s arguably our single most important piece of developer docs and programmers new to GLib should review it regularly as it can be tricky to learn how to use GMainContext properly. After a while, it will feel more intuitive.

Thank you both for the quick responses.

I missed this line in the docs:

GMainContext is completely thread safe, meaning that a GSource can be created in one thread and attached to a GMainContext running in another thread.

I’ll check out gio for examples.

Appreciate your help!

Note you do not usually need a MainContext in a work thread in Rust, unless you plan to also await glib/gio futures in that thread. A work thread in Rust typically will only use some native async primitives and a queue like the ones in crossbeam and perform the work that way.

1 Like

Thanks for explaining this.

Since I’m using Rust, It seems like avoiding glib in the worker thread might be the best approach.

I looked into crossbeam and it seems like the deque describes what I need.

Thanks again for the reply.

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