Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peterson's Algorithm on C++ multithreading

I've written a simple implementation for Peterson's Algorithm in C++ with multi threading. This program changes the string through two threads. But I'm not getting the final result. Where am I wrong?

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;
}
like image 747
Adnan Avatar asked Sep 26 '26 03:09

Adnan


1 Answers

Prior to C++11 there was no threading model in C++. After C++11, your code does unordered access to the same variable causing race conditions.

Race conditions result in undefined behavior.

Changing a std::string is not atomic. You cannot do it safely while other threads are reading or writing from it.

In C++11 the threading primitives of std are a better idea than the above raw pthread code, excluding the very rare features you cannot emulate.

like image 146
Yakk - Adam Nevraumont Avatar answered Sep 28 '26 16:09

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!