Reputation: 3605
I'm confused about how threads and synchronization works. I am working through a sample problem that is described like so:
There are two threads: P and Q. The variable, counter, is shared by both threads. Modification of counter in one thread is visible to the other thread. The increment instruction adds one to the variable, storing the new value.
1 global integer counter = 0
2
3 thread P()
4 incr(counter)
5 print counter
6 end
7
8 thread Q()
9 print counter
10 incr(counter)
11 print counter
12 incr(counter)
13 end
There are three print statements that output the value of counter. In the output list below, indicate whether the given output is possible and if it is, give the interleaving instructions (using thread and line numbers) of P and Q that can lead to the output.
The example has output 122 is it possible? which can be produced by P4, Q9, Q10, P5, Q11, Q12
. I can't wrap my head around how this works.
Upvotes: 2
Views: 176
Reputation: 847
Assume thread P starts first and increments "counter" by one. Then it's suspended and thread Q starts, reads "counter" and prints its value ("1"). Next thread Q increments "counter", which is now "2". Then thread Q gets suspended and thread P continues. It now reads "counter" and prints its value ("2"). Thread P terminates. Thread Q continues, reads and prints "counter" ("2"). It then increments "counter" by one.
The output therefore is: "122"
That's one possible sequence of execution. Generally speaking you can never tell when a thread gets suspended and when it continues, that's the whole point of this exercise. By adding synchronization mechanisms (which this example is completely lacking) you can get control over the sequence of execution again.
Upvotes: 4