Thread interleaving scenario

Viewed 88

I am trying to get my head around some interleavings and am playing around with some code. I have the following code

volatile int num;

First thread:
num = 10;
num = num + 5; 

Second thread:
num = 20;
num = num - 1;

Would I be right in saying that there would be 24 possible interleavings (possible orders of execution sequences) of the code if both threads concurrently run. Also, would there only be two possibilities if num is no longer volatile and both threads run while holding the same lock?

1 Answers

Without any locking, all interleavings are possible. So:

a: num = 10;
b: num + 5; 
c: num = b

d: num = 20;
e: num - 1;
f: num = e

In all executions, abc and def are ordered, so:

abcdef
abdcef
adbcef
dabcef
dabecf
daebcf
deabcf
deabfc
deafbc
defabc

If you use a lock enclosing (abc) and (def), then:

abcdef
defabc
Related