Consider the following scenario:
Thread 1 ID : 1
Thread 2 ID : 2
Following steps would take place:
Thread 1 gets CPU cycle and executeschat(1)
flag=1
x = 1 : since flag == 1 soyo
is printed
Thread 1 is preempted by Thread 2
Thread 2 gets CPU cycle and executeschat(2)
flag = 1 (NOT 2 becauseflag==0
condition fails)
x = 1 : since flag!=2 sodude
will be printed
x = 2 : since flag!=2 sodude
will be printed
Thread 1 gets the CPU cycle
flag = 1
x = 2 : since flag == 1 soyo
will be printed.
Hence the output is `yo dude dude yo`