Reputation: 821
part 1:
Here is a problem from a quiz on edx RiceX: COMP322 Fundamentals of Parallel Programming/Topic 1.1 Quiz:
3.Consider the following pseudo-code program.
a = b = 0
async {
a = 3;
b = 5;
}
async {
a = 4;
b = 4;
}
x = a + b
At the end, x could have various different values. How many different values are possible for x?
There is a statement in the explanation:
Since the code within each async executes sequentially, it's impossible to get the sum x = 0 + 5 = 5.
part 2:
Here is the quote from the book Java Concurrency in Practice
on a similar problem:
The actions in each thread have no dataflow dependence on each other, and accordingly can be executed out of order. (Even if they are executed in order, the timing by which caches are flushed to main memory can make it appear, from the perspective of B, that the assignments in A occurred in the opposite order.
According to the statement above, I think it is possible for x=a+b
in main thread to see a
of value 0
and b
of value 5
because the two actions: a=3;
and b=5;
can be executed out of order. And even if a=3;
and b=5;
is executed in order, from the perspective of the main thread, it may still see b
of value 5 and not seeing a
of value 3 because of the flushing issue mentioned above.
So, which answer should I believe? Is the explanation of the quiz wrong? Is it java specific?
Upvotes: 1
Views: 172
Reputation: 718758
So, which answer should I believe? Is the explanation of the quiz wrong? Is it java specific?
Based on the context that I can see1, the Quiz answer and explanation are self-consistent. It is using / describing a model of concurrency that is different from Java's.
The quote from Goetz et al is correct for Java, but this example code is not written in Java.
1 - The link is only readable by people who are signed up for that course.
Upvotes: 1