CriticalSection

CriticalSection[var,expr]

locks the variable var with respect to parallel computation, evaluates expr, then releases 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.

Examples

open allclose all

Basic Examples  (1)

Protect a block of code from interference by other threads:

Without protecting access to the update code, subkernels may overwrite results:

Generalizations & Extensions  (1)

Lock variables can be of the form sym[index]:

Applications  (1)

Separate read and write operations are not thread-safe:

Use CriticalSection to make a whole code section atomic:

Properties & Relations  (2)

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:

Possible Issues  (1)

Lock variables must not have a value before being used in a critical section:

A deadlock can be broken with an abort:

Neat Examples  (1)

The dining philosophers, deadlock-free:

Wolfram Research (2008), CriticalSection, Wolfram Language function, https://reference.wolfram.com/language/ref/CriticalSection.html (updated 2020).

Text

Wolfram Research (2008), CriticalSection, Wolfram Language function, https://reference.wolfram.com/language/ref/CriticalSection.html (updated 2020).

BibTeX

@misc{reference.wolfram_2020_criticalsection, author="Wolfram Research", title="{CriticalSection}", year="2020", howpublished="\url{https://reference.wolfram.com/language/ref/CriticalSection.html}", note=[Accessed: 03-December-2020 ]}

BibLaTeX

@online{reference.wolfram_2020_criticalsection, organization={Wolfram Research}, title={CriticalSection}, year={2020}, url={https://reference.wolfram.com/language/ref/CriticalSection.html}, note=[Accessed: 03-December-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