Search code examples
multithreadingglobal-variablesatomic

How to explain Read/Write global variables in multi threads environment


I am not familiar with multi-thread and locks and atomic/nonatomic operations.

Recently I saw an interview question as below.

Put f1 and f2 in two separate threads and run them at the same time, when both of them return, what is the value of a?

int a = 2, b = 0, c = 0
func f1()
{
    a = a * 2
    a = b
}
func f2()
{
    c = a + 11
    a = c
}

I tried to implement the above code in objective c environment and what I got is a = 11. I'm not sure if this is right since what I did is put f1 in main queue and put f2 in a dispatch global queue and ran it async which could be incorrect.

If someone could give an answer and explain the process based on the level of register accessing, CPU processing, memory usage, that would be great.


Solution

  • The answer is - the result of A is random. It can be anything. Since access to A is not atomic and there is no synchronization, different threads might see a different value for a depending on random factors. If you manage to make a unaligned and run it on X86, you might even see a non-value for a.