snowrain
snowrain

Reputation: 442

Atomic variable c++

I have count initialized as

count = 15;

and if I have two threads like this:

thread_1(){
    count = 0;
    x = count;
    count = x;
}

and

thread_2(){
    y = count;
    count = y;
    count = 0;
}

Without count being synchronized, count can end up being 15 after running the two threads.

If I declare my count variable as atomic, will count always be 0 after running the two threads?

Upvotes: 2

Views: 435

Answers (2)

C_Elegans
C_Elegans

Reputation: 1133

No. First of all, your operations are likely already atomic, as in they change count all at once. C++ atomics are really for things like count = count + 5, where you need to load count, add 5 to it, and store it back. Instead, what you need is to make each of those sections atomic, and for that you can use a std::mutex, like so:

int count = 15;
std::mutex mutex;

void thread_1(void){
    //Locks the mutex and unlocks when it goes out of scope
    std::lock_guard<std::mutex> guard(mutex); 
    count = 0;
    x = count;
    count = x;
}
void thread_2(void){
    //alternatively:
    mutex.lock()
    y = count;
    count = y;
    count = 0;
    mutex.unlock()
}

Upvotes: 0

ensc
ensc

Reputation: 6994

no; program can be executed like

  1. count = 15 (global initialization)
  2. y = count (thread2)
  3. count = 0 (thread1)
  4. count = y (thread2 -> 15)
  5. x = count (thread1)
  6. count = 0 (thread2)
  7. count = x (thread1 -> 15)

Upvotes: 5

Related Questions