declares the symbols si as shared variables whose values are synchronized among all parallel kernels.
- The unique value of a shared variable is maintained by the master kernel and every access on a parallel subkernel is synchronized through the master kernel.
- Shared variables without a value evaluate to Null.
Examplesopen allclose all
Basic Examples (1)
Access a single element of a shared list efficiently:
Assign a new value to a shared variable:
Only the last assignment performed remains:
Change a single element of a shared list:
Update the value of a shared variable:
Generalizations & Extensions (1)
Use shared variables to synchronize input and output in an infinite search:
Find such that is prime, until the computation is manually aborted:
Use a shared variable to signal all evaluations to stop as soon as a prime has been found:
Use a shared variable to hand out tasks to do:
Monitor the progress of a calculation, counting major calculation steps:
Return results as they are found:
Properties & Relations (1)
$KernelCount is effectively a shared variable:
Possible Issues (2)
Separate read and write operations are not thread-safe:
Use atomic updates for synchronization:
Alternatively, use CriticalSection to make a whole code section atomic:
Create a shared variable whose value is a large matrix:
Accessing its elements causes the whole matrix to be transferred to the subkernels repeatedly:
Use Unevaluated to allow the special code for parts of shared variables to see the variable:
Wolfram Research (2008), SetSharedVariable, Wolfram Language function, https://reference.wolfram.com/language/ref/SetSharedVariable.html.
Wolfram Language. 2008. "SetSharedVariable." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/SetSharedVariable.html.
Wolfram Language. (2008). SetSharedVariable. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/SetSharedVariable.html