我正在使用全局变量实现线程间通信。是赋值运算符'='原子?
//global var
volatile bool is_true = true;
//thread 1
void thread_1()
{
while(1){
int rint = rand() % 10;
if(is_true) {
cout << "thread_1: "<< rint <<endl; //thread_1 prints some stuff
if(rint == 3)
is_true = false; //here, tells thread_2 to start printing stuff
}
}
}
//thread 2
void thread_2()
{
while(1){
int rint = rand() % 10;
if(! is_true) { //if is_true == false
cout << "thread_1: "<< rint <<endl; //thread_2 prints some stuff
if(rint == 7) //7
is_true = true; //here, tells thread_1 to start printing stuff
}
}
}
int main()
{
HANDLE t1 = CreateThread(0,0, thread_1, 0,0,0);
HANDLE t2 = CreateThread(0,0, thread_2, 0,0,0);
Sleep(9999999);
return 0;
}
问题
在上面的代码中,我使用全局变量volatile bool is_true
切换thread_1和thread_2之间打印。
我不知道这里是否使用赋值操作是线程安全的?
我宁愿使用原子交换原语,但我不能解决你会遇到问题的场景...... –
@KerrekSB,这个场景?那么,我只是简单地展示了我的问题,:) – Alcott
嗯,我的意思是一系列的加载和存储将被充分打破,使两个线程进入关键部分...通常应该能够展示这样一个序列以说明为什么某些代码不正确。虽然我在这里看不到它。我仍然不喜欢代码,但我无法证明为什么。 –