简体   繁体   中英

Possible value of Variable when given two threads are running parallely?

The problem is from question paper at Stanford. The description of it is as follows:

Suppose two threads execute the following C code concurrently, accessing shared variables a, b, and c:


int a = 4;
int b = 0;
int c = 0;


if (a < 0) { 
 c = b - a;
} else {
 c = b + a;
}


b = 10;
a = -3

What are the possible values for c after both threads complete? You can assume that reads and writes of the variables are atomic, and that the order of statements within each thread is preserved in the code generated by the C compiler.

I understood the first four outputs as follows, but I'm not able to understand how the output -3 can occur given that order of statements within the thread is preserved.

: Execute thread 1 completely, then execute thread 2. :执行完线程1,再执行线程2。
: Interrupt thread 1 before c = b + a , and then execute thread 2, followed by executing thread 1 again. : 在c = b + a之前中断线程 1,然后执行线程 2,然后再次执行线程 1。
: Execute thread 2 till b = 10 is done, then interrupt it, and execute thread 1 completely. : 执行线程2,直到b = 10完成,然后中断它,并完全执行线程1。
: Execute thread 2 completely, then thread 1. :完全执行线程2,然后执行线程1。

Now I'm stuck on how to obtain -3 as a final value of c ? -3 is only possible when b=0 , and a=-3 , and thread 1 starts its execution from c = b + a . I don't see -3 to be possible in any other case. But as mentioned in question, order of statements is maintained, so the value of a can not be -3, unless we change the value of b to 10.

Can someone explain how the output -3 is possible in this case?

You can get -3 as follows:

  1. In thread 1, check a < 0 , which is false. This takes you to the else condition. Read the value of b , which is 0 .
  2. Switch to thread 2, execute it completely. a is now -3 .
  3. Switch back to thread 1, read a , which is -3 . Then, add and assign -3 to c .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM