我想在C++中模拟竞争条件。下面是我的代码,我使用了Xcode作为我的IDE竞争条件模拟崩溃在xcode
相关的代码是这样的:
int main(int argc, const char * argv[])
{
int value=0;
int* ptr = &value;
racer r1(ptr, "John");
racer r2(ptr, "Mike");
std::thread my_thread1(r1);
std::thread my_thread2(r2);
//guard g1(my_thread1);
//guard g2(my_thread2);
my_thread1.join();
my_thread2.join();
cout<<"result:= "<<*ptr<<endl;
cout <<"end!"<<endl;
return 0;
}
,为赛车手,我有:
racer::racer(int* r, char const* name)
{
this->r=r;
this->name=name;
}
void racer::print_result()
{
cout<<this->name<<" "<<*r<<endl;
}
void racer::count_now()
{
for (int i = 0; i < 50; i++)
{
*r = *r + 1;
cout<<this->name<<". "<<*r<<endl;
}
}
void racer::operator()()
{
count_now();
}
所以基本上,没有竞争我的预期结果是* ptr = 100,因为有2个线程在同一资源上一起运行。所以有时当我运行它时,我得到了100,有时它崩溃了,我得到下面的错误信息。这是为什么?换句话说,为什么我不能得到大于100的值?当它崩溃是否意味着我有一个竞争条件,从而出现错误?
代码在我的linux上工作正常。 – ROTOGG
@Leon Li您是否得到了> 100的结果? – adhg