In C++, I feel like I've always been lead to believe that things like var++ and var-- are reasonably threadsafe - AKA - you have a guarantee that your value will increase or decrease at some point in time.
It was upon this belief that I built my understanding of non-blocking algorithms for thread-safe operations. Yet, today I'm in shock, as I have a variable that is not getting incremented - and am therefore questioning the validity of a large amount of my past work.
In a small program, I have a global variable initialized at 0. Eight P-Threads are started up that each call varname++ a total of 1024 times, totalling to 8*1024 increments. Yet after all threads have finished executing, the value of varname is significantly less than 8*1024.
Did I miss the boat here? Can someone please enlighten me?
What exactly would lead you to the belief those where threadsafe? In general they are not. The reason for that is simple: Arithmetic is generally done on registers, so var++ might be transformed to something like the following:
load var to R1
inc R1
store R1 to var
If another thread modifies var between the load and the store you will obviously loose that update. In reality this problem will be even worse, since the compiler can decide to keep the variable in a register for as long as it wants (well for as long as it can prove that var isn't accessed through any pointers to it (in the same thread)).
Having multiple threads access the same variable is defined to be a data race (and therefore undefined behaviour) by the (C++11) standard, unless none of the thread modifies the variable (if all do read access only, you are fine).
For threadsafety operations, you need to use either locking (e.g. using std::mutex in C++11) or atomic operations. If you use C++11, you can use std::atomic<int> (or whatever type your counter is) as the type for var to get threadsafe modifications. (Arithmetic) Operations on std::atomic<T> (like the increment and decrement operators) are guaranteed to be threadsafe by the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With