std/sync

The std/sync module provides a comprehensive suite of synchronization primitives for managing concurrent access to shared data and coordinating thread execution.

Overview

Usage

import "std/sync.zc"
import "std/io.zc"

fn main() {
    let m = Mutex::new();
    
    // Scoped lock (RAII)
    {
        m.lock();
        // Critical section
        m.unlock();
    } // m is freed automatically if it was the last owner
    
    // One-time initialization
    let once = Once::new();
    once.call(fn() {
        println("Initialized!");
    });
}

Struct Definitions

Mutex

A mutual exclusion lock for protecting shared data.

CondVar

A condition variable for signaling between threads based on state changes.

RwLock

A reader-writer lock that allows multiple concurrent readers but only one writer.

Once

Ensures that a specific piece of initialization code is executed exactly once.

Semaphore

A counting semaphore for controlling access to a pool of resources.

Barrier

A synchronization point where multiple threads must wait until a specific number have arrived.

Methods

Mutex Methods

MethodSignatureDescription
newMutex::new() -> MutexCreates a new mutex.
locklock(self)Acquires the lock (blocking).
try_locktry_lock(self) -> boolAttempts to acquire the lock without blocking.
unlockunlock(self)Releases the lock.

CondVar Methods

MethodSignatureDescription
newCondVar::new() -> CondVarCreates a new condition variable.
waitwait(self, mutex: Mutex*)Blocks the thread until signaled, releasing the mutex temporarily.
signalsignal(self)Wakes up one thread waiting on this condition.
broadcastbroadcast(self)Wakes up all threads waiting on this condition.

RwLock Methods

MethodSignatureDescription
newRwLock::new() -> RwLockCreates a new reader-writer lock.
rdlockrdlock(self)Acquires a shared read lock.
wrlockwrlock(self)Acquires an exclusive write lock.
unlockunlock(self)Releases any lock held.

Semaphore Methods

MethodSignatureDescription
newSemaphore::new(value: int) -> SemaphoreCreates a new semaphore with initial value.
waitwait(self)Decrements the semaphore (blocking if 0).
postpost(self)Increments the semaphore.
valuevalue(self) -> intReturns the current value.

Barrier Methods

MethodSignatureDescription
newBarrier::new(count: int) -> BarrierCreates a new barrier for count threads.
waitwait(self) -> boolWaits at the barrier. Returns true for the designated leader.

Memory Management

All primitives implement impl Drop and will automatically call their internal free() method to release system resources when they go out of scope.