I wrote this piece of code
#include /* Input/Output */
#include /* General Utilities */
#include
Your 2 threads access a shared resource without protection thus a race conditions apply. The increase operation isn't atomic, so you can actually have something like this in terms of machine operations:
Thread 1 Thread 2
Load value of cnt
Load value of cnt
Increase value of cnt
Write value of cnt Increase value of cnt
Write value of cnt
Note, that although both threads have increased the cnt
, it was actually increased only by 1.
If you want the result to be deterministic, you need to protect the shared resource (cnt
), e.g. by locking it prior to access.