c++ - 如果 pthread_cond_signal 是线程中的最后一次调用,是否存在数据竞争?

标签 c++ multithreading synchronization posix

使用 -fsanitize=thread 编译它会产生 pthread_cond_signalpthread_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/

相关文章:

c++ - 使用 new 运算符返回指针。删除该放在哪里?

Python 线程未启动

Android 线程和 ArrayAdapter

java - 是否可以使用 JUnit 测试多线程?

sql - 为什么 SQL 数据同步需要 SQL Server 本地数据库上的 Alter Database 权限?

java - Java中同一对象的不同实例上的多线程

C++ - 将 int 转换为 bytes 并编写相应的测试方法

c++ - 这个流命令如何在 C++ 中读取整个文件?

c++ - eglSwapBuffers 永远不会返回

c++ - 通过不同线程使用迭代器迭代 STL 映射