Skip to content

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.Result
Console.WriteLine($"{t.IsAlive}")
Console.WriteLineInt(t.Id)

Static Methods

Thread.Sleep(500) // sleep for 500 ms
Thread.Yield() // yield to scheduler
int 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) // 2000

Mutex Methods

MethodDescription
m.Lock()Acquire the lock (blocks until available)
m.Unlock()Release the lock
m.TryLock()Try to acquire; returns bool