I use GLib/GObject and am facing the following problem:
I have a class my_class
that will have several object instances in multiple threads during runtime, where each object will exist within a single thread (so there is a 1:1 relation between the thread and the object).
However, the object will access a shared resource and I need locking to protect access to that resource. Now, I need a global mutex (a GMutex
in GLib world) instance, that is available to all threads/objects to lock onto.
My current approach is to create that mutex before the threads are spawned, and pass that global mutex along in the constructor. But I don't like that approach. The mutex is not of any concern of the calling code before creating the threads - it is only required for functionality by the my_class
and should as such then only be part of the my_class
for a clean OO design.
But how to create a single mutex from within my_class
? I could create a static GMutex *global_mutex
and have it as global variable, shared across all threads. But when/how to call g_mutex_new()
? I'd like to have it in the constructor of my_class
, but the code needs only to be run once. To achieve that, I need locking in the first place, and I face an Chicken-Egg problem.
What you want is a GStaticMutex
. Declare it as a static local variable in the thread function, and initialize it with G_STATIC_MUTEX_INIT
:
static GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
This declares, defines and initializes the mutex, so it can be used directly.
See the example in the linked reference.