Lock
Lock Statement
The lock statement acquires a mutex, executes a body, and releases the mutex on all exit paths:
Mutex m = Mutex();
lock(m){ sharedData = sharedData + 1;}// m is automatically unlockedSingle-statement form:
lock(m) sharedData = sharedData + 1;Early Exit Safety
The mutex is released on all exit paths — normal completion, exceptions, and early returns:
lock(m){ if (condition) { return 42; } // m unlocked before return}Nested Locks
Mutex m1 = Mutex();Mutex m2 = Mutex();
lock(m1){ lock(m2) { // both m1 and m2 held } // m2 released, m1 still held}Qualifier Chaining
lock can combine with atomic and unsafe in any order:
lock(m) atomic { counter += 1; } // lock + atomic (no try/catch)lock(m) unsafe { ... } // lock + unsafeunsafe lock(m) { ... } // order doesn't matterLockable Types
The lockable modifier embeds a mutex directly in a GC-allocated type:
lockable type SharedCounter{ int count;
SharedCounter() { this.count = 0; }
void Increment() { this.count = this.count + 1; }}
SharedCounter! c = new SharedCounter();
lock(c){ c.Increment(); // mutex held during access}Lockable Inheritance
Lockability is inherited by derived types. Only the root lockable type reserves the mutex slot:
lockable type Base{ int x;}
type Derived : Base{ int y;}
Derived! d = new Derived();lock(d) { d.x = 10; } // uses Base's embedded mutex