使用 -fsanitize=thread
编译它会产生 pthread_cond_signal
和 pthread_cond_destroy
之间的数据竞争报告:
#include <stdio.h>
#include <pthread.h>
#include <err.h>
bool done = false;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func(void *)
{
pthread_mutex_lock(&mutex);
done = true;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
return NULL;
}
int main()
{
pthread_t thread;
pthread_cond_init(&cond, NULL);
pthread_mutex_init(&mutex, NULL);
if (pthread_create(&thread, NULL, func, NULL) != 0)
err(1, "pthread_create()");
pthread_mutex_lock(&mutex);
while (!done)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
pthread_join(thread, NULL);
return 0;
}
如果我在 pthread_cond_signal
之后调用 pthread_mutex_unlock
,报告就会消失。但是手册说 pthread_cond_signal
不需要获取互斥量。是否在任何地方记录了调用 pthread_cond_signal
作为引用 pthread_cond_t
的最后一次调用,并从执行 pthread_cond_wait
的线程中销毁它是不合法的?
最佳答案
Is it documented anywhere that calling pthread_cond_signal as the last call that references a pthread_cond_t, and destroying it from the thread that does pthread_cond_wait is not legal ?
它们无法涵盖文档中的所有极端情况。是的,在互斥体解锁后调用 pthread_cond_signal()
是合法的,在可以调用 pthread_cond_signal()
的同时销毁它是不合法的。
关于c++ - 如果 pthread_cond_signal 是线程中的最后一次调用,是否存在数据竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47308494/