gpt4 book ai didi

c++ - Peterson 的 C++ 多线程算法

转载 作者:太空狗 更新时间:2023-10-29 21:38:03 26 4
gpt4 key购买 nike

我用多线程用 C++ 编写了 Peterson 算法的简单实现。该程序通过两个线程更改字符串。但我没有得到最终结果。我哪里错了?

using namespace std;

int flag[2]={0,1};
int turn;

void* first(void* data){
flag[0]=1;
turn=1;
while(flag[1] && turn==1){}
string &str=*(static_cast<string*>(data));
if(str!=""){
if(str=="abcd"){
str="Hello";
}
}
flag[0]=0;
pthread_exit(NULL);
}

void* second(void* data){
flag[1]=1;
turn=0;
while(flag[0] && turn==0){}
string &str=*(static_cast<string*>(data));
if(str!=""){
if(str=="wxyz"){
str="abcd";
}
}
flag[1]=0;
pthread_exit(NULL);
}

int main(){
int rc=0;
string s = "wxyz";
pthread_t t;

rc=pthread_create(&t,NULL,first,static_cast<void*>(&s));
if(rc!=0){
cout<<"error!";
exit(rc);
}
rc=pthread_create(&t,NULL,second,static_cast<void*>(&s));
if(rc!=0){
cout<<"error!";
exit(rc);
}

while(flag[0] && flag[1]!=0){}
cout<<s;

pthread_exit(NULL);
return 0;
}

最佳答案

在 C++11 之前,C++ 中没有线程模型。在 C++11 之后,您的代码会无序访问同一变量,从而导致竞争条件。

竞争条件导致未定义的行为。

改变 std::string 不是原子的。当其他线程正在读取或写入它时,您无法安全地执行此操作。

在 C++11 中,std 的线程原语比上面的原始 pthread 代码更好,排除了您无法模拟的非常罕见的功能。

关于c++ - Peterson 的 C++ 多线程算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com