Previous: Unstructured Termination Up: Unstructured Parallelism: spawn Next: Pitfalls
The same rules that apply to sharing mutable variables in parallel blocks and parfor apply to spawn as well. Usually, the pass-by-value semantics of function calls in C and C++ prevents such sharing.
{ int i = 1; spawn incr(i); i++; spawn incr(i); }
There is no dangerous sharing of variables here because each instance of incr() has its own copy of the value of i.
However, care must be taken when pointers (or C++ references) are used in function arguments. This can lead to inadvertent, dangerous sharing of mutable variables.
{ int a = 1; spawn f(&a); //DANGER: possible sharing of mutable a \ if (a==1) {...} } //end of a's scope, so spawned thread could reference garbage
Even if a is not explicitly modified by either f() or the spawning thread, this example illustrates another possible danger. The scope of the variable a is defined in the spawning thread. Without an explicitly programmed barrier, the variable a could reach the end of its scope and be implicitly destroyed in the spawning thread, leaving f() with an invalid pointer.