小编xsl*_*slr的帖子

当只有一个线程写入c ++中的bool变量时,是否存在竞争条件?

在下面的代码示例中,程序执行永远不会结束.

它创建一个线程,在终止之前等待全局bool设置true.只有一位作家和一位读者.我相信允许循环继续运行的唯一情况是bool变量是否为false.

这怎么可能是bool变量,最终处于不一致的状态只是一个作家

#include <iostream>
#include <pthread.h>
#include <unistd.h>

bool done = false;

void * threadfunc1(void *) {
    std::cout << "t1:start" << std::endl;
    while(!done);
    std::cout << "t1:done" << std::endl;

    return NULL;
}

int main()
{
    pthread_t threads;

    pthread_create(&threads, NULL, threadfunc1, NULL);

    sleep(1);

    done = true;
    std::cout << "done set to true" << std::endl;

    pthread_exit(NULL);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ multithreading synchronization race-condition

7
推荐指数
1
解决办法
1596
查看次数