Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to synchronize primitives in C++

I have a volatile bool 'play' flag in my class that is being set by one thread and being read by another thread.

Do I need to synchronize the calls to that flag? for example in this function:

void stop() 
{
   play = false;
}

In windows they have the _InterlockedExchange and OSX has OSAtomicAdd64Barrier, I've seen those functions being used with shared primitives, do I need them?

Thank you

like image 807
kambi Avatar asked Jan 25 '26 09:01

kambi


1 Answers

Yes, and volatile does not in any way imply thread safe or atomic. Use std::mutex and std::unique_lock etc if you can, not the platform specifics. std::atomic is good choice -- maybe even best in this case.

like image 59
Brandon Avatar answered Jan 27 '26 23:01

Brandon



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!