I am using C++11 and have a general question. I have a counter to count number of messages received so it's just a simple "count = count + 1" but my co-worker said I should put a mutex around it. I would think this simple operation only takes a few assembly instructions and it's impossible to be preempted by another thread. I'd like to hear input from experts. Thanks.
Asked
Active
Viewed 46 times
0
-
See also https://stackoverflow.com/questions/4628243/is-the-operator-thread-safe – NineBerry Nov 24 '19 at 23:47
-
1Even if it took only one instruction (which it might, especially on x86), that would not make it atomic. – harold Nov 24 '19 at 23:49
-
@harold, interesting. Taking the terminology of *micro operations* from [this answer](https://stackoverflow.com/a/1091448/7151494), would your statement also hold true for those, so called, *micro operations*? – Fureeish Nov 24 '19 at 23:54
-
@Fureeish even then, for example a store that is split by a cache line boundary is still a single µop but not atomic – harold Nov 25 '19 at 00:15
-
@harold, thank you, that is a completely new way of seeing this. So, in essence, a cache miss may result in a few additional operations that may introduce time for other threads to be scheduled? And atomic operations take that into accout? If yes, do you have any sources that would expand on the topic further? – Fureeish Nov 25 '19 at 00:17
-
2@Fureeish well keep in mind that we're already some decades into the multi-core age, an other thread *is already running* on some other core (or even on the same core, with HyperThreading). So atomicity is more a property intentionally generated by the hardware, than something that spontaneously comes into being by an operation being "too small to interrupt" (which is how it used to be, back in the day). – harold Nov 25 '19 at 00:25