acquires the lock var for parallel computation, evaluates expr, then releases the lock var.


locks all variables vari simultaneously.


  • 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].


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:

Scope  (2)

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

Use two indexed lock variables to protect the source and destination indices of an update operation:

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)

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

The deadlock that occurs when the lock variable does have a value can be broken with an abort:

Neat Examples  (1)

The dining philosophers, deadlock-free:

Wolfram Research (2008), CriticalSection, Wolfram Language function, (updated 2020).


Wolfram Research (2008), CriticalSection, Wolfram Language function, (updated 2020).


Wolfram Language. 2008. "CriticalSection." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2020.


Wolfram Language. (2008). CriticalSection. Wolfram Language & System Documentation Center. Retrieved from


@misc{reference.wolfram_2024_criticalsection, author="Wolfram Research", title="{CriticalSection}", year="2020", howpublished="\url{}", note=[Accessed: 25-July-2024 ]}


@online{reference.wolfram_2024_criticalsection, organization={Wolfram Research}, title={CriticalSection}, year={2020}, url={}, note=[Accessed: 25-July-2024 ]}