我有以下代码片段。请注意,我有多个生产者和只有一个消费者。
pthread_mutex_t mutex;
pthread_cond_t cv;
// producer thread
if (pthread_mutex_lock(&mutex) != 0)
{
log(LOG_ERR, "pthread_mutex_lock: %s (%d)", strerror(errno), errno);
}
// do something
if (pthread_mutex_unlock(&mutex) != 0)
{
log(LOG_ERR, "pthread_mutex_unlock: %s (%d)", strerror(errno), errno);
}
if (pthread_cond_signal(&cv) != 0)
{
log(LOG_ERR, "pthread_cond_signal: %s (%d)", strerror(errno), errno);
}
// consumer thread
if (pthread_mutex_lock(&mutex) != 0)
{
log(LOG_ERR, "pthread_mutex_lock: %s (%d)", strerror(errno), errno);
}
while (1)
{
if (variable)
{
break;
}
if (pthread_cond_wait(&cv, &mutex) != 0)
{
log(LOG_ERR, "pthread_cond_wait: %s (%d)", strerror(errno), errno);
}
}
// do something
if (pthread_mutex_unlock(&mutex) != 0)
{
log(LOG_ERR, "pthread_mutex_unlock: %s (%d)", strerror(errno), errno);
}
起初,它运行得很好,但过了一会儿,所有生产者都挂在 pthread_cond_signal 上,而消费者挂在 pthread_cond_wait 上,我使用 gdb Attach 验证了这一点。日志没有报任何错误。
下面是 strace 的输出,没有输出更新。
$ strace -k -p 1234567
strace: Process 1234567 attached
futex(0x635ff0, FUTEX_WAIT_PRIVATE, 2, NULL
以前,我注意到 futex 有时会返回 EAGAIN,但由于 pthread_mutex_lock 不会返回错误,我认为这很好(在此处讨论)。
variable
的值变为 true,但生产者没有设置它。
pthread_mutex_lock(&mutex);
variable = 1; // Missing.
pthread_cond_signal(&cv); // Usually done within the mutex area.
pthread_mutex_unlock(&mutex);