Threading
Overview
Cera provides OS-level threads through the Thread type and synchronization via Mutex.
Creating Threads
Pass a callable to the Thread constructor:
Thread t = Thread(fn(){ Console.WriteLine("Hello from thread!")})t.Join()Thread Properties
Thread t = Thread(fn(){ Console.WriteLineInt(Thread.CurrentId())})t.Join()
int result = t.ResultConsole.WriteLine($"{t.IsAlive}")Console.WriteLineInt(t.Id)Static Methods
Thread.Sleep(500) // sleep for 500 msThread.Yield() // yield to schedulerint id = Thread.CurrentId()int cores = Thread.ProcessorCount()Mutex
A Mutex prevents concurrent access to shared state:
Mutex m = Mutex()int shared = 0
Thread t1 = Thread(fn(){ for (int i : [0..1000]) { m.Lock() shared = shared + 1 m.Unlock() }})
Thread t2 = Thread(fn(){ for (int i : [0..1000]) { m.Lock() shared = shared + 1 m.Unlock() }})
t1.Join()t2.Join()Console.WriteLineInt(shared) // 2000Mutex Methods
| Method | Description |
|---|---|
m.Lock() | Acquire the lock (blocks until available) |
m.Unlock() | Release the lock |
m.TryLock() | Try to acquire; returns bool |