vendredi 23 octobre 2020

Difference between atomic

I want to know if there is any different between std::atomic<int> and int if we are just doing load and store. I am not concerned about the memory ordering. For example consider the below code

int x{1};

void f(int myid) {

    while(1){
        while(x!= myid){}
        //cout<<"thread : "<< myid<<"\n";
        //this_thread::sleep_for(std::chrono::duration(3s));
        x = (x % 3) + 1;
    }
}

int main(){

    thread x[3];
    for(int i=0;i<3;i++){

        x[i] = thread(f,i+1);
    }

    for(int i=0;i<3;i++){

        x[i].join();
    }
}

Now the output (if you uncomment the cout) will be

Thread :1

Thread :2

Thread :3

...

I want to know if there is any benefit in changing the int x to atomic<int> x?

Aucun commentaire:

Enregistrer un commentaire