In a multi-threaded program where 2 threads –
thread 1 – will run a loop that increases an integer variable 1000 times and then exits
thread 2 – will run a loop that decreases an integer variable 1000 times and then exits
Both threads wait on a semaphore and start roughly at the same time and are scheduled to run on different cores approximately same time.
After both the threads exit, will the value of the integer variable will be zero?
Note: no locking(mutex etc..) is used
Let us assume linux and x86 architecture and multi-core hardware.
What happens for above if the same integer is declared as volatile (C++) ?
If more than one thread modifies the same memory location at the same time the program has a data race and the effects are undefined. The result can be pretty much anything, assuming you get a result at all. For simple variables like integer types, atomics will eliminate the data race and provide proper synchronization. Use
atomic_int(also known asatomic<int>).