CriticalSection
CriticalSection[var,expr]
acquires the lock var for parallel computation, evaluates expr, then releases the lock var.
CriticalSection[{var1,var2,…},expr]
locks all variables vari simultaneously.
Details
- At most one instance of a critical section with the same lock variable is allowed to run concurrently on any parallel kernel.
- Variables used as locks should not have a value in the master kernel.
- WithLock[var,expr] is equivalent to CriticalSection[var,expr].
Examples
open allclose allBasic Examples (1)
Scope (2)
Applications (1)
Separate read and write operations are not thread-safe:
Use CriticalSection to make a whole code section atomic:
Properties & Relations (3)
Locks are acquired by writing the kernel's ID into the lock variable:
Shared functions can be used for synchronization in place of a critical section:
Less efficient is the use of a shared variable and critical section:
WithLock works the same way as CriticalSection does with symbols:
Possible Issues (1)
Text
Wolfram Research (2008), CriticalSection, Wolfram Language function, https://reference.wolfram.com/language/ref/CriticalSection.html (updated 2020).
CMS
Wolfram Language. 2008. "CriticalSection." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2020. https://reference.wolfram.com/language/ref/CriticalSection.html.
APA
Wolfram Language. (2008). CriticalSection. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/CriticalSection.html