Mutex
A mutual exclusion lock for coordinating access to shared resources.
Only one process can hold a Mutex at a time. The preferred usage is
critical:, which acquires the lock, evaluates a block, and
guarantees the lock is released afterward.
Mutex new isLocked "=> false"
Mutex new tryLock "=> true"
| m <Mutex> |
m := Mutex new.
m lock.
m unlock.
m isLocked "=> false"
Mutex new critical: [42] "=> 42"
"Protecting a shared counter across processes"
| count <Integer> mutex <Mutex> wg <WaitGroup> |
count := 0.
mutex := Mutex new.
wg := WaitGroup new.
1 to: 10 do: [:i |
wg wrap: [mutex critical: [count := count + 1]]
].
wg wait.
count
Class Methods
primitives
uncategorized
Create a new, unlocked Mutex.
Mutex new isLocked "=> false"
Instance Methods
primitives
uncategorized
Evaluate aBlock while holding the lock. The lock is
automatically released when the block finishes, even if an
error occurs. This is the preferred way to use a Mutex.
Mutex new critical: [42] "=> 42"
Mutex new critical: [3 + 4] "=> 7"
| m <Mutex> |
m := Mutex new.
m critical: ['done'].
m isLocked "=> false"
Execute aBlock only if the lock can be acquired immediately.
Returns the block's result if executed, or nil if the lock
was already held.
Mutex new ifAvailable: [42] "=> 42"
| m <Mutex> |
m := Mutex new.
m lock.
m ifAvailable: [42] "=> nil"
Return true if the mutex is currently locked.
Mutex new isLocked "=> false"
Acquire the lock. Blocks the caller if the mutex is already held by another process.
| m <Mutex> |
m := Mutex new.
m lock.
m isLocked "=> true"
Return a string describing the mutex and its state.
Mutex new printString "=> 'a Mutex (unlocked)'"
Try to acquire the lock without blocking. Returns true if
the lock was acquired, false if it was already held.
Mutex new tryLock "=> true"
| m <Mutex> |
m := Mutex new.
m lock.
m tryLock "=> false"
Release the lock, allowing other processes to acquire it.
| m <Mutex> |
m := Mutex new.
m lock.
m unlock.
m isLocked "=> false"
Alias for critical:. Evaluate aBlock while holding the lock.
Mutex new withLock: [42] "=> 42"