Will this sample code for g_cond_wait () lead to undefined behavior?

This is an example from 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;
}

Now let's move on to the following:

  • The first call flow pop_data(), data_mutexblocked (1)
  • g_cond_wait()called, data_mutexunlocked (2), the first thread is waiting
  • Second thread call push_data(), data_mutexblocked (3)
  • The second thread signals the first that the waiting condition is met, unlocks data_mutex(4)
  • The first thread wakes up, exits g_cond_wait()and unlocks data_mutexagain (5)

The docs say unlocking a non-locked mutex is undefined. Does this mean that the example contains an error? Or g_cond_wait()block mutexes before exiting?

+4
2

, undefined. , ? g_cond_wait() ?

. , . g_cond_wait() , .

Thread1 g_cond_wait() g_cond_wait() . thread2 , thread1, g_cond_wait(). thread1 , (thread2 ). g_mutex_unlock() thread2 , g_cond_wait() thread1 , .

+4

, . glib docs g_cond_wait():

, .

+2

All Articles