Reputation: 442
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
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
Reputation: 6994
no; program can be executed like
count = 15
(global initialization)y = count
(thread2)count = 0
(thread1)count = y
(thread2 -> 15)x = count
(thread1)count = 0
(thread2)count = x
(thread1 -> 15)Upvotes: 5