@sync

The @sync module provides synchronization primitives for thread-safe access to shared data. Compiler-only feature; requires POSIX threads.

Import

import @sync

Functions

mutex()

() -> Mutex

Creates a new mutex.

import @sync

do main() {
    mut mtx = sync.mutex()
    ensure sync.destroy(mtx)

    // Use the mutex...
}

lock()

(m Mutex)

Acquires a mutex. Blocks until the mutex is available.

sync.lock(mtx)
// Critical section...
sync.unlock(mtx)

unlock()

(m Mutex)

Releases a mutex.

sync.unlock(mtx)

destroy()

(m Mutex)

Destroys a mutex and frees its resources.

sync.destroy(mtx)

Example Program

import @threads
import @sync

do main() {
    mut mtx = sync.mutex()
    ensure sync.destroy(mtx)

    mut shared = 0

    do worker() {
        for i in range(0, 100) {
            sync.lock(mtx)
            shared++
            sync.unlock(mtx)
        }
    }

    mut t1 = threads.spawn(()worker)
    mut t2 = threads.spawn(()worker)

    threads.join(t1)
    threads.join(t2)

    println("Final value:", shared)  // 200
}