Previous: Definition Up: Sharing Data
The above definition may appear redundant. However, in Chapter
Now for the rule:
If a mutable variable is modified in a thread of a parallel block, then no other thread of control in the parallel block should make use of that variable (either by writing or by reading the variable).
The following example illustrates the point.
{ int x; par { x = 1; //dangerous sharing x = 2; //dangerous sharing } }
This parallel block violates the sharing rule for mutable variables. The mutable integer variable x is modified in both statements of the parallel block. Though this code may not result in a compile-time error, or even necessarily a run-time error, it is extremely dangerous. This is because at the end of the parallel block we can say nothing about the value of x. It could be 1, or 2, or something completely different! If mutable variables are shared in this manner between parallel threads of control, it is almost certainly a programming error.
Not only should at most one thread of control modify the value of a mutable variable, but if a mutable variable is modified in one thread, then no other thread should access the value of that variable. For example:
{ int n,s; par { s = 3; //dangerous sharing n = 2*s; //dangerous sharing } }
Here the first statement in the parallel block initializes the value of the mutable variable s, and the second statement uses the value of s. Again, this does not necessarily result in a run-time error, but it is almost certainly a programming error, since we can say nothing about the value of n (or even s for that matter) at the end of the parallel block. Notice that both examples above are correct sequential programs when the keyword par is removed. The programmer should therefore take care when parallelizing sequential code that no inadvertent sharing of mutable data is created by the creation of parallel blocks.
So the only safe kind of sharing of mutable data between parallel
threads of control is multiple reading of the variable. Examples
of this kind are given in Sections and
. Make sure you understand why these
examples do not involve dangerous sharing of mutable variables
and are indeed correct parallel programs. In Chapter
we introduce a mechanism for controlling access to shared
mutables, and in Chapter
we introduce a new kind of variable that can be shared
between parallel threads of control in a different manner.