在下面的代码示例中,程序执行永远不会结束。
它创建一个线程,该线程在终止之前等待全局 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;
}
最佳答案
从某种意义上说,threadfunc1()
中的这条语句存在问题:
while(!done);
可以由编译器实现为:
a_register = done;
label:
if (a_register == 0) goto label;
因此永远不会看到对done
的更新。
关于c++ - 当只有一个线程写入 c++ 中的 bool 变量时,是否可能出现竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21183261/