Today I came across this question:
you have a code
static int counter = 0;
void worker() {
for (int i = 1; i <= 10; i++)
counter++;
}
If worker
would be called from two different threads, what value will counter
have after both of them are finished?
I know that actually it could be anything. But my internal guts tells me, that counter++
will most likely be translated into single assembler instruction, and if both threads are execute on the same core, counter
will be 20.
But what if those threads are run on different cores or processors, could there be a race condition in their microcode? Is one assembler instruction could always be viewed as atomic operation?