This is an example from the Glib docs for g_cond_wait()
:
gpointer current_data = NULL;
GMutex data_mutex;
GCond data_cond;
void push_data (gpointer data)
{
g_mutex_lock (&data_mutex); // (3)
current_data = data;
g_cond_signal (&data_cond);
g_mutex_unlock (&data_mutex); // (4)
}
gpointer pop_data (void)
{
gpointer data;
g_mutex_lock (&data_mutex); // (1)
while (!current_data)
g_cond_wait (&data_cond, &data_mutex); // (2)
data = current_data;
current_data = NULL;
g_mutex_unlock (&data_mutex); // (5)
return data;
}
Let's now go through this:
- First thread calls
pop_data()
,data_mutex
is locked (1) g_cond_wait()
is called,data_mutex
is unlocked (2), first thread is waiting- Second thread calls
push_data()
,data_mutex
is locked (3) - Second thread signals the first one that the wait condition is satisfied, unlocks
data_mutex
(4) - First thread wakes up, exits from
g_cond_wait()
and unlocksdata_mutex
again (5)
The docs say that unlocking a non-locked mutex is undefined. Does this mean the example contains a bug? Or will g_cond_wait()
lock the mutex before exiting?