WithLock[LocalSymbol["name"],expr]
locks the local symbol name, evaluates expr, then releases the local symbol.
WithLock[var,expr]
locks the shared variable var, evaluates expr, then releases the shared variable.
WithLock
WithLock[LocalSymbol["name"],expr]
locks the local symbol name, evaluates expr, then releases the local symbol.
WithLock[var,expr]
locks the shared variable var, evaluates expr, then releases the shared variable.
Details and Options
- WithLock locks a File or LocalSymbol by creating it. WithLock releases the File or LocalSymbol by deleting it.
- If the lock object is already locked, WithLock will wait until the lock is released.
- Locking is atomic; at most, one process can lock an object, thus ensuring it evaluates expr exclusively.
- WithLock has attribute HoldAll.
- The following options can be given:
-
TimeConstraint Infinity how long to wait for the lock to become available ExpirationDate None when the lock should expire PersistenceTime Infinity how long the lock should remain valid - If the lock cannot be obtained within the time given by TimeConstraint, WithLock returns $TimedOut and does not evaluate expr.
- A lock that has reached its expiration date or lifetime will be considered unlocked by the next WithLock that attempts to lock it. ExpirationDate gives an absolute date/time for expiration; PersistenceTime gives a relative time.
- WithLock[var,expr] uses a shared variable for locking among parallel subkernels. It is equivalent to CriticalSection[var,expr].
- When used on different computers, lock files must reside on a shared file system available to all computers where WithLock is run.
Examples
open all close allBasic Examples (2)
Prepare to access a file by many concurrent processes:
file = CreateFile[]Protect concurrent access with a lock file in the same directory:
lock = file <> "-lck"Use several parallel processes to try to write to the same file concurrently:
With[{file = file, lock = lock},
ParallelEvaluate[WithLock[File[lock], PutAppend[$KernelID, file]]]
];The data has been written (in a nondeterministic order) without interference among the processes:
ReadList[file]Initialize a file by writing 0 into it:
file = CreateFile[];Put[0, file]Concurrently read the file and write an updated value:
With[{file = file, lock = file <> "-lck"},
ParallelEvaluate[WithLock[File[lock], v = Get[file] + 1;Put[v, file];v]]
]All accesses have effectively been serialized:
Get[file]Unprotected concurrent accesses may overwrite each other's values and even read partial content:
Put[0, file]With[{file = file},
ParallelEvaluate[v = Get[file] + 1;Put[v, file];v]
]Scope (3)
File Locking (1)
Use a lock file to serialize a concurrent update operation:
LocalSymbol["counter"] = 0;With[{file = "/tmp/lockfile"},
ParallelEvaluate[WithLock[File[file], LocalSymbol["counter"] = LocalSymbol["counter"] + 1]]]LocalSymbol["counter"]LocalSymbol Locking (1)
Options (3)
ExpirationDate (1)
A lock can be set to expire, to protect against the locking process being unable to release the lock:
WithLock[File["/tmp/lock"], expr, ExpirationDate -> Now + Quantity[10, "Seconds"]]A lock that was not released carries identifying information:
Get["/tmp/lock"]Once it has expired, the next WithLock to use it will break the lock:
WithLock[File["/tmp/lock"], Print["success"]]PersistenceTime (1)
A lock can be set to expire, to protect against the locking process being unable to release the lock:
WithLock[File["/tmp/lock"], expr, PersistenceTime -> 10]A lock that was not released carries identifying information:
Get["/tmp/lock"]Once it has expired, the next WithLock to use it will break the lock:
WithLock[File["/tmp/lock"], Print["success"]]TimeConstraint (1)
If a lock is taken, WithLock will wait forever and will need to be aborted:
lock = CreateFile[];WithLock[File[lock], Print["inside lock"]]Give a finite timeout value to limit the time spent waiting for the lock to become available:
WithLock[File[lock], Print["inside lock"], TimeConstraint -> 2]Properties & Relations (2)
Using a shared variable in WithLock is equivalent to CriticalSection:
ParallelEvaluate[WithLock[locksym, Put[$KernelID, "/tmp/output"]]];ParallelEvaluate[CriticalSection[locksym, Put[$KernelID, "/tmp/output"]]];Get["/tmp/output"]Update operations on local symbols are automatically protected from concurrency:
LocalSymbol["counter"] = 0;ParallelEvaluate[LocalSymbol["counter"]++]LocalSymbol["counter"]Possible Issues (4)
If a file used as a lock already exists, the locking will hang:
lock = CreateFile[]This evaluation will not return until it is aborted:
WithLock[File[lock], Print["inside lock"]]Always use a nonexisting file as a lock:
WithLock[File[lock <> ".lck"], Print["inside lock"]]If a local symbol used as a lock has a value, the locking will hang:
LocalSymbol["/tmp/lock"] = 0;This evaluation will not return until it is aborted:
WithLock[LocalSymbol["/tmp/lock"], Print["inside lock"]]Always use a nonexisting local symbol as a lock:
Remove[LocalSymbol["/tmp/lock"]]WithLock[LocalSymbol["/tmp/lock"], Print["inside lock"]]Not all file systems support the required operation for local symbol locking:
$LocalSymbolBaseWithLock[LocalSymbol["lock"], Print["inside lock"]]File locks are supported in more cases:
WithLock[File["lock"], Print["inside lock"]]Launch parallel kernels on the local and one remote machine:
LaunchKernels[{KernelConfiguration["Local", "KernelCount" -> 4], KernelConfiguration["andromeda", "KernelCount" -> 4]}];$KernelCountFiles and lock files created on a local file system may not be available on remote machines:
file = CreateFile[]
lock = file <> ".lck"Concurrently write to file on all parallel subkernels:
With[{lock = File[lock], file = file},
ParallelEvaluate[WithLock[lock, PutAppend[{$MachineName, $KernelID}, file];$KernelID]]]Only the results from the local kernels are available in the file:
FilePrint[file]The results from the remote machine have been written to a file local to that machine:
RemoteEvaluate["andromeda", FilePrint[file]]Use a file and lock file on a shared file system:
file = FileNameJoin[{$HomeDirectory, "output.txt"}]
lock = file <> ".lck"Concurrently write to file on all parallel subkernels:
With[{lock = File[lock], file = file},
ParallelEvaluate[WithLock[lock, PutAppend[{$MachineName, $KernelID}, file];$KernelID]]]Now, all results are written to the same file:
FilePrint[file]Related Guides
History
Text
Wolfram Research (2021), WithLock, Wolfram Language function, https://reference.wolfram.com/language/ref/WithLock.html.
CMS
Wolfram Language. 2021. "WithLock." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/WithLock.html.
APA
Wolfram Language. (2021). WithLock. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/WithLock.html
BibTeX
@misc{reference.wolfram_2026_withlock, author="Wolfram Research", title="{WithLock}", year="2021", howpublished="\url{https://reference.wolfram.com/language/ref/WithLock.html}", note=[Accessed: 13-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_withlock, organization={Wolfram Research}, title={WithLock}, year={2021}, url={https://reference.wolfram.com/language/ref/WithLock.html}, note=[Accessed: 13-June-2026]}