Docs/Standard library

sync

Protect shared state with mutexes and wait for groups of native threads to finish.

Zero-value synchronization#

sync provides Mutex and WaitGroup for native threads, with APIs similar to Go’s. Both work from zero values and use pointer receivers, so calls on addressable variables automatically borrow their address. Keep each value at a stable address and never copy it after first use.

Use mutexes to protect shared mutable data. Successful locking and waiting make the synchronized writes visible to the waiting thread. Function captures share storage; they do not themselves provide synchronization.

These types use the same native backend as threads: pthreads on Linux/macOS and Win32 synchronization on Windows. Compilation for WebAssembly fails. Native state is initialized lazily and retained until process shutdown.

Zero-value synchronization reference
TypeMethods
MutexLock(), Unlock(), TryLock() bool
WaitGroupAdd(delta int), Done(), Wait()

sync.Mutex#

Lock() blocks until it acquires the mutex. Mutexes are nonrecursive: trying to Lock a mutex you already hold blocks. TryLock() returns true when it acquires ownership and false when ownership is unavailable. A failed TryLock does not grant access to the protected data.

Unlock() releases the mutex. Unlocking an unlocked mutex panics. Like Go, a mutex is not tied to an owner thread; another thread may unlock it. There is no fairness guarantee.

Register a deferred Unlock immediately after acquiring the mutex when Return or Kill can occur. Mutex waits check cancellation and release internal synchronization before unwinding.

Ocean
package main;
import "sync";

func main() {
    mutex: sync.Mutex;
    mutex.Lock();
    defer mutex.Unlock();
    // Access protected state here.
}

sync.WaitGroup#

Add(delta int) changes the outstanding work count. Call Add with a positive count before spawning the corresponding work. Done() is equivalent to Add(-1). Wait() blocks until the count reaches zero and returns immediately if it is already zero. Multiple threads can Wait on the same group.

A negative counter or counter overflow panics. Reuse a group only after all Wait calls from the preceding group have returned; starting new work from zero while those waiters are still returning panics. Adding more work while the counter is positive is supported.

Register a deferred Done for each task so Return or cancellation can finish its contribution. Wait checks cancellation, removes the cancelled waiter, and runs the thread’s deferred cleanup. A wait group tracks work completion; use threads.Await as well when you need to join the native worker.

Ocean
package main;
import "io";
import "sync";
import "threads";

func main() {
    mutex: sync.Mutex;
    done: sync.WaitGroup;
    total := 0;
    done.Add(4);
    ids := int[]{};
    for (i := 0; i < 4; i++) {
        id := threads.Spawn(func() {
            defer done.Done();
            mutex.Lock();
            defer mutex.Unlock();
            total++;
        });
        ids.append(id);
    }
    done.Wait();
    for (index, id := range ids) threads.Await(id);
    io.Println(total).unwrap(); // 4
}