xsl*_*slr 7 c++ multithreading synchronization race-condition
在下面的代码示例中,程序执行永远不会结束.
它创建一个线程,在终止之前等待全局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)
从某种意义上讲,这个陈述存在一个问题 threadfunc1():
while(!done);
Run Code Online (Sandbox Code Playgroud)
可以由编译器实现如下:
a_register = done;
label:
if (a_register == 0) goto label;
Run Code Online (Sandbox Code Playgroud)
所以done永远不会看到更新.