Mutex

Inherits from: Object

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.

Example
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"
Example
"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

class primNew

uncategorized

class new

Create a new, unlocked Mutex.

Example
Mutex new isLocked  "=> false"

Instance Methods

primitives

primCritical:
primIsLocked
primLock
primTryLock
primUnlock

uncategorized

critical:

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.

Example
Mutex new critical: [42]       "=> 42"
Mutex new critical: [3 + 4]    "=> 7"

| m <Mutex> |
m := Mutex new.
m critical: ['done'].
m isLocked                     "=> false"
ifAvailable:

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.

Example
Mutex new ifAvailable: [42]    "=> 42"

| m <Mutex> |
m := Mutex new.
m lock.
m ifAvailable: [42]            "=> nil"
isLocked

Return true if the mutex is currently locked.

Example
Mutex new isLocked  "=> false"
lock

Acquire the lock. Blocks the caller if the mutex is already held by another process.

Example
| m <Mutex> |
m := Mutex new.
m lock.
m isLocked  "=> true"
printString

Return a string describing the mutex and its state.

Example
Mutex new printString  "=> 'a Mutex (unlocked)'"
tryLock

Try to acquire the lock without blocking. Returns true if the lock was acquired, false if it was already held.

Example
Mutex new tryLock             "=> true"

| m <Mutex> |
m := Mutex new.
m lock.
m tryLock                     "=> false"
unlock

Release the lock, allowing other processes to acquire it.

Example
| m <Mutex> |
m := Mutex new.
m lock.
m unlock.
m isLocked  "=> false"
withLock:

Alias for critical:. Evaluate aBlock while holding the lock.

Example
Mutex new withLock: [42]  "=> 42"