Mutexes, condition variables, wait groups, read-write locks, semaphores and once, for coordinating threads.
import sync
When several threads change the same variable they have to take turns, or the result depends on the order the threads happen to run in. The sync package has the classic tools for taking turns, built on the operating system's threads library:
•
A mutex: each thread takes the lock before touching the data and releases it afterwards. An RWMutex lets many readers in at once.
•
A condition variable: a thread sleeps until another one says that something has changed.
•
A wait group: call Add before starting a piece of work, Done at its end, and Wait until the count is back to zero.
•
A semaphore caps how many threads are inside a part at once, and a once runs setup a single time.
Threads themselves come from spawn and the thread package. For a single shared number, atomic is cheaper than a lock; to hand values from one thread to another, chan does the locking and waiting for you; to cancel work, ctx.
The things people get wrong:
•
Using a value that was never created. Every tool here is made with a New... function; a zero sync.Mutex {} has no lock inside and crashes on Lock. Globals are declared with {} and created at the top of main.
•
Locking twice. A mutex is not reentrant: a thread that calls Lock on a mutex it already holds waits forever. Do holds a lock while its function runs, so calling Do on the same Once from inside it hangs too.
•
Waiting on a condition without a loop. WaitCond can return before the condition is true; always wait inside until not condition:.
•
Forgetting Destroy.... Each tool holds operating system memory; destroy it after the last thread that uses it has been joined.
Keep data consistent with a mutex
A lock is not only for counters. Anything that has to stay true across several variables, such as "the money in all accounts adds up to the same total", needs every change to happen while the lock is held. Take the lock at the top of the function and put Unlock in a defer, so it is released on every return path, including the early ret.
sync-guide-transfer.salam
import sync
mut accounts := Vector {} asVector<int>
mut lock := sync.Mutex {}
mut group := sync.WaitGroup {}
functransfer(from: int, dest: int, amount: int): bool:
sync.Lock(lock)
defer sync.Unlock(lock)
if accounts.Get(from) < amount:
retfalseend
accounts.Set(from, accounts.Get(from) - amount)
accounts.Set(dest, accounts.Get(dest) + amount)
rettrueendfuncclerk():
repeat1000in i:
transfer(i % 3, (i + 1) % 3, 7)
end
sync.Done(group)
endfuncmain:
lock = sync.NewMutex()
group = sync.NewWaitGroup()
accounts.Push(500)
accounts.Push(300)
accounts.Push(200)
sync.Add(group, 4)
mut workers := Vector {} asVector<i64>
defer workers.Free()
repeat4:
workers.Push(spawn(clerk))
end
sync.Wait(group)
each t in workers:
join(t)
end
total := accounts.Get(0) + accounts.Get(1) + accounts.Get(2)
println"money in the bank:", total
println"a transfer that is too big:", transfer(0, 1, 100000)
accounts.Free()
sync.DestroyWaitGroup(group)
sync.Destroy(lock)
end
Output
money in the bank: 1000
a transfer that is too big: false
Four threads move money around 4000 times and the total is still 1000. Without the lock two threads could read the same balance at once and one of the changes would be lost.
Many readers, few writers
When data is read far more often than it is changed, such as settings or a cache, a plain mutex makes readers wait for each other for no reason. An RWMutex lets any number of readers in together with RLock, and gives a writer the data to itself with WLock.
A reader must never write while holding only the read lock. If a reader may need to change the data, take the write lock instead.
Limit how many run at once
A Semaphore holds a number of permits. Acquire takes one and waits when none are left, Release gives it back. With two permits, at most two threads are inside the guarded part at any moment, which is how you cap parallel downloads or database connections.
sync-guide-limit.salam
import sync
mut slots := sync.Semaphore {}
mut lock := sync.Mutex {}
mut running := 0mut busiest := 0mut finished := 0funcdownload():
sync.Acquire(slots)
sync.Lock(lock)
running++
if running > busiest:
busiest = running
end
sync.Unlock(lock)
sync.SleepMs(20)
sync.Lock(lock)
running--
finished++
sync.Unlock(lock)
sync.Release(slots)
endfuncmain:
slots = sync.NewSemaphore(2)
lock = sync.NewMutex()
mut jobs := Vector {} asVector<i64>
defer jobs.Free()
repeat6:
jobs.Push(spawn(download))
endeach t in jobs:
join(t)
endprintln"downloads finished:", finished
println"never more than two at once:", busiest <= 2
sync.Destroy(lock)
sync.DestroySemaphore(slots)
end
Output
downloads finished: 6
never more than two at once: true
TryAcquire takes a permit only if one is free and returns false at once otherwise, for work that should be skipped rather than queued.
Set something up exactly once
Some setup is expensive and should happen only when it is first needed, but several threads may need it at the same moment. Do runs its function the first time it is called on a Once; every other caller waits until that run has finished and then goes on without running it again.
A condition variable is how a thread sleeps until there is something to do instead of checking in a busy loop. The workers below wait on has_work while the queue is empty, and the main thread calls Signal after each push to wake one of them. A wait group counts the jobs: Add before each push, Done when it is processed, and Wait returns when all are done. To stop the workers, set a flag and Broadcast, which wakes all of them.
sync-guide-queue.salam
import sync
mut lock := sync.Mutex {}
mut has_work := sync.CondVar {}
mut jobs_done := sync.WaitGroup {}
mut queue := Vector {} asVector<int>
mut taken := 0mut closed := falsemut total := 0funcworker():
sync.Lock(lock)
untiltrue:
until taken == queue.Len() andnot closed:
sync.WaitCond(has_work, lock)
endif taken == queue.Len(): breakendsize := queue.Get(taken)
taken++
sync.Unlock(lock)
cost := size * 2
sync.Lock(lock)
total += cost
sync.Done(jobs_done)
end
sync.Unlock(lock)
endfuncmain:
lock = sync.NewMutex()
has_work = sync.NewCondVar()
jobs_done = sync.NewWaitGroup()
workers := [spawn(worker), spawn(worker), spawn(worker)]
repeat1to10insize:
sync.Add(jobs_done, 1)
sync.Lock(lock)
queue.Push(size)
sync.Signal(has_work)
sync.Unlock(lock)
end
sync.Wait(jobs_done)
println"all 10 jobs done, total cost", total
sync.Lock(lock)
println"nobody signals, waited 20 ms, woken:", sync.WaitCondTimeout(has_work, lock, 20)
closed = true
sync.Broadcast(has_work)
sync.Unlock(lock)
each t in workers: join(t) endprintln"workers stopped"
queue.Free()
sync.DestroyWaitGroup(jobs_done)
sync.DestroyCondVar(has_work)
sync.Destroy(lock)
end
Output
all 10 jobs done, total cost 110
nobody signals, waited 20 ms, woken: false
workers stopped
WaitCond releases the lock while it sleeps and takes it again before it returns, which is why the worker can check the queue right after it. WaitCondTimeout does the same with a time limit, returning true when it was woken and false when the time ran out. The wait group does not replace join: every spawned thread still has to be joined once.
Pitfalls, and which tool to use
•
When two locks are needed, every thread must take them in the same order. Taking A then B in one thread and B then A in another can stop both.
•
Keep the locked part short. Do slow work, such as file or network calls, before taking the lock or after releasing it.
•
Every New... has a matching Destroy.... Call it after the last thread using the value has been joined.
Runs the function only if this is the first time; other threads wait until it finishes. It holds a lock while the function runs, so the function must not call Do on the same Once.
The example for this item is shown with the ones above: sync-RWMutex.salam