g_cond_wait() 的示例代码会导致未定义的行为吗?

Will this example code for g_cond_wait() lead to undefined behaviour?

这是 g_cond_wait() 的 Glib 文档中的示例:

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;
}

现在让我们来看看这个:

文档说解锁未锁定的互斥锁是未定义的。这是否意味着该示例包含错误?或者 g_cond_wait() 会在退出前锁定互斥锁吗?

是的,等待后互斥量再次被锁定。来自 g_cond_wait():

的 glib 文档

When this function returns, mutex is locked again and owned by the calling thread.

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?

这里没有错误。没有解锁未锁定在代码中的互斥锁。 g_cond_wait() 将在 returns 时锁定互斥量。

Thread1 调用 g_cond_wait() 并锁定了互斥量,g_cond_wait() 自动解锁互斥量并等待条件。在此之后,thread2 锁定互斥量并执行操作,然后 signals 给在 g_cond_wait() 中等待的 thread1。但是 thread1 无法继续,因为 mutex 仍然不可用(thread2 尚未解锁)。因此,在线程 2 中的调用 g_mutex_unlock() 将其解锁后,线程 1 中的 g_cond_wait() 锁定了互斥锁并调用 returns.