A channel for passing values from one thread to another, with a buffer, timeouts and closing.
import chan
A channel is a queue that several threads send values into at one end and receive from at the other; it handles the locks and the waiting for you. You give the value type when you create it, as in chan.Chan<i64>, and call init with a capacity before using it.
When the buffer is full, send waits; when it is empty, recv does. A channel of capacity zero is "unbuffered": the sender waits until a receiver takes the value. After close, sending returns false but receivers still get the values that are left; once the channel is empty, ok turns false and a receiving loop can end.
Use a channel when one thread produces values and another consumes them. For shared data that several threads change in place, sync is the better fit; for a counter, atomic; for running the turns of a loop on every core, pool; and for telling workers to stop, ctx.
The things people get wrong:
•
Forgetting init. A channel declared with chan.Chan {} has no buffer or lock yet and crashes on the first send.
•
Using the value from a failed receive. When ok is false the result is a zero value that means nothing.
•
Telling a timeout from the end. recv_timeout sets ok to false both when the time ran out and when the channel is closed and empty; ask is_closed to know which.
•
Sending a Vector or a pointer and then changing it. The channel copies the value, which for those types is only the handle, so both threads see the same memory.
The receive loop
Almost every consumer looks the same: receive in an endless until true: loop and break when ok turns false. That happens only after the channel is closed and empty, so no value is lost. The rule that goes with it: the side that sends is the side that closes, once it has nothing more to send.
chan-guide-loop.salam
import chan
mut orders := chan.Chan {} as chan.Chan<str>
funccheckout():
each id in ["A-1001", "A-1002", "A-1003"]:
orders.Send(id)
end
orders.Close()
println"after close, send works:", orders.Send("A-1004")
endfuncmain:
orders.Init(8)
t := spawn(checkout)
join(t)
println"waiting in the buffer:", orders.Len()
mut ok := trueuntiltrue:
id := orders.Recv(ok)
ifnot ok: breakendprintln"packing", id
endprintln"closed and empty:", orders.IsClosed(), orders.Len()
orders.Free()
end
Output
after close, send works: false
waiting in the buffer: 3
packing A-1001
packing A-1002
packing A-1003
closed and empty: true 0
The sender filled the buffer and closed the channel before the receiver even started, and still every order came out. A send after close returns false instead of waiting.
A pipeline of stages
Channels connect stages that each do one thing. Here one thread generates numbers, a second squares them, and the main thread adds them up. Each stage closes its output channel when its input runs dry, so the end of the data flows down the pipeline by itself and every loop stops on its own.
chan-guide-pipeline.salam
import chan
mut numbers := chan.Chan {} as chan.Chan<i64>
mut squares := chan.Chan {} as chan.Chan<i64>
funcgenerate():
repeat1to10in n:
numbers.Send(n asi64)
end
numbers.Close()
endfuncsquare():
mut ok := trueuntiltrue:
n := numbers.Recv(ok)
ifnot ok:
breakend
squares.Send(n * n)
end
squares.Close()
endfuncmain:
numbers.Init(2)
squares.Init(2)
a := spawn(generate)
b := spawn(square)
mut total := 0asi64mut count := 0mut ok := trueuntiltrue:
v := squares.Recv(ok)
ifnot ok:
breakend
total += v
count++
endjoin(a)
join(b)
println"values through the pipeline:", count
println"sum of squares:", total
numbers.Free()
squares.Free()
end
Output
values through the pipeline: 10
sum of squares: 385
The channels hold only two values each. When the last stage is slow, the earlier ones wait in send instead of piling up memory, which is called back pressure.
Ask and wait for an answer
Two channels make a request and reply pair: one carries questions to a worker, the other brings the answers back. With capacity zero, each send waits until the other side has taken the value, so the two threads move in step and the answers come back in the order the questions went out.
chan-guide-reply.salam
import chan
mut requests := chan.Chan {} as chan.Chan<str>
mut replies := chan.Chan {} as chan.Chan<str>
funcserver():
mut ok := trueuntiltrue:
name := requests.Recv(ok)
ifnot ok:
breakend
replies.Send("hello, " + name)
endendfuncmain:
requests.Init(0)
replies.Init(0)
t := spawn(server)
mut ok := trueeach name in ["Sara", "Reza", "Mina"]:
requests.Send(name)
println replies.Recv(ok)
end
requests.Close()
join(t)
requests.Free()
replies.Free()
end
Output
hello, Sara
hello, Reza
hello, Mina
Many senders, one receiver
When several threads send into one channel, none of them can close it, because each one only knows that it is done. Count the senders with a sync.WaitGroup and let one more small thread wait for the group and then close the channel.
chan-guide-fanin.salam
import chan
import sync
mut events := chan.Chan {} as chan.Chan<i64>
mut senders := sync.WaitGroup {}
funcsensor(base: i64):
repeat5in i:
events.Send(base + i asi64)
end
sync.Done(senders)
endfuncsensor_a(): sensor(100) endfuncsensor_b(): sensor(200) endfuncsensor_c(): sensor(300) endfunccloser():
sync.Wait(senders)
events.Close()
endfuncmain:
events.Init(4)
senders = sync.NewWaitGroup()
sync.Add(senders, 3)
a := spawn(sensor_a)
b := spawn(sensor_b)
c := spawn(sensor_c)
d := spawn(closer)
mut per_sensor := [0, 0, 0]
mut ok := trueuntiltrue:
v := events.Recv(ok)
ifnot ok:
breakend
per_sensor[v / 100 - 1]++
endjoin(a)
join(b)
join(c)
join(d)
println"from sensor a:", per_sensor[0]
println"from sensor b:", per_sensor[1]
println"from sensor c:", per_sensor[2]
sync.DestroyWaitGroup(senders)
events.Free()
end
Output
from sensor a: 5
from sensor b: 5
from sensor c: 5
Values from different senders arrive interleaved in no fixed order, so the program counts them per sender instead of printing them as they come.
When the channel is full
send waits for room, which is not always what you want. A server under load is often better off refusing extra work at once than making every caller wait. try_send returns false immediately when there is no room, and try_recv does the same for an empty channel.
chan-guide-shed.salam
import chan
funcmain:
mut queue := chan.Chan {} as chan.Chan<int>
queue.Init(3)
mut accepted := 0mut dropped := 0repeat1to8in request:
if queue.TrySend(request):
accepted++
else:
dropped++
endendprintln"accepted:", accepted, "dropped:", dropped, "waiting:", queue.Len()
mut ok := trueuntiltrue:
r := queue.TryRecv(ok)
ifnot ok:
breakendprintln"handling request", r
endprintln"queue empty:", queue.Len() == 0
queue.Free()
end
Between the two extremes are send_timeout and recv_timeout, which wait at most the given number of milliseconds.
If the channel is full or empty
Send
Receive
Wait as long as it takes
send
recv
Wait up to some milliseconds
send_timeout
recv_timeout
Do not wait at all
try_send
try_recv
Two mistakes to avoid: receiving from a channel nobody will ever close or send to waits forever, and calling free while another thread is still using the channel. Join the threads first, then free.
A shorter way to spell it
New builds an initialized channel, so the cast is the only extra spelling: c := chan.New(8) as chan.Chan<i64>. The free functions Send, Recv, TrySend, TryRecv, Close, Len, Capacity and IsClosed take the channel as their first argument and do exactly what the method of the same name does. SendAll sends a whole vector and stops at the first failure; Take receives up to a count; and Drain receives everything that is left until the channel is closed and empty.
chan-API.salam
import chan
funcmain:
c := chan.New(3) as chan.Chan<str>
println"capacity:", chan.Capacity(c), "len:", chan.Len(c)
words := Vector {} asVector<str>
words.Push("one")
words.Push("two")
println"sent:", chan.SendAll(c, words)
println"queued:", chan.Len(c)
words.Free()
mut ok := falseprintln"first:", chan.Recv(c, ok), ok
println"next:", chan.TryRecv(c, ok), ok
chan.Close(c)
println"closed:", chan.IsClosed(c), "send:", chan.TrySend(c, "late")
left := chan.Drain(c)
println"left:", left.Len()
left.Free()
c.Free()
end
Output
capacity: 3 len: 0
sent: true
queued: 2
first: one true
next: two true
closed: true send: false
left: 0
SelectRecv is Select with the ok result, and SelectSend waits for the first channel of the vector with room, returning its index, minus one on timeout or minus two when every channel is closed. A zero millisecond limit makes either one a single non-blocking attempt; TrySelect and TrySelectSend are the same thing with the zero already filled in.
Drain and Take wait like recv, so close the channel before draining it and ask for no more values than will arrive. SelectSend only sends to a buffered channel with room: on an unbuffered channel try_send is always false, so give that channel a buffer or use a plain send from a thread.
The internal state: the head and tail of the queue, the count and whether it is closed.
cap
i64 = 0
The capacity.
zidx
i64 = 0
The buffer slot holding the type's zero value, for when nothing was received.
mu
sync.Mutex
The internal lock.
not_empty
sync.CondVar
Waking the receivers.
not_full
sync.CondVar
Waking the senders.
taken
sync.CondVar
The signal that a value was taken, on an unbuffered channel.
chan-Chan.salam
import chan
import sync
mut jobs := chan.Chan {} as chan.Chan<i64>
mut results := chan.Chan {} as chan.Chan<i64>
mut group := sync.WaitGroup {}
funcworker():
mut open := trueuntiltrue:
n := jobs.Recv(open)
ifnot open:
breakend
results.Send(n * n)
end
sync.Done(group)
endfuncmain:
jobs.Init(4)
results.Init(16)
group = sync.NewWaitGroup()
sync.Add(group, 2)
a := spawn(worker)
b := spawn(worker)
repeat1to11in n:
jobs.Send(n)
end
jobs.Close()
sync.Wait(group)
join(a)
join(b)
results.Close()
mut total := 0asi64mut open := trueuntiltrue:
v := results.Recv(open)
ifnot open:
breakend
total += v
endprintln"sum of the squares:", total
println jobs.IsClosed(), jobs.Len(), jobs.Capacity(), jobs.Send(1)
sync.DestroyWaitGroup(group)
jobs.Free()
results.Free()
end
Sends a value, waiting when there is no room; on an unbuffered channel it waits until a receiver has taken it. If the channel is closed, or is closed while it waits, it returns false.
The example for this item is shown with the ones above: chan-Chan.salam
Receives a value, waiting when there is none. When the channel is closed and empty, ok turns false; the returned value then means nothing and must not be used.
The example for this item is shown with the ones above: chan-Chan.salam
Creates a channel with the given capacity and returns it initialized; zero means unbuffered. Write the type on the result, as in chan.New(4) as chan.Chan<i64>.
chan-API.salam
import chan
funcmain:
c := chan.New(3) as chan.Chan<str>
println"capacity:", chan.Capacity(c), "len:", chan.Len(c)
words := Vector {} asVector<str>
words.Push("one")
words.Push("two")
println"sent:", chan.SendAll(c, words)
println"queued:", chan.Len(c)
words.Free()
mut ok := falseprintln"first:", chan.Recv(c, ok), ok
println"next:", chan.TryRecv(c, ok), ok
chan.Close(c)
println"closed:", chan.IsClosed(c), "send:", chan.TrySend(c, "late")
left := chan.Drain(c)
println"left:", left.Len()
left.Free()
c.Free()
end
Output
capacity: 3 len: 0
sent: true
queued: 2
first: one true
next: two true
closed: true send: false
left: 0
funcSelect<T>(cs: Vector<Chan<T>>, v &: T, ms: i64): i64
Waits for the first ready channel of a vector of channels without polling: the caller sleeps until a send or a close wakes it. Returns its index and stores the value; -1 when the time in milliseconds runs out (a negative time waits forever), -2 when every channel is closed and empty.
chan-Select.salam
import chan
import pool
funcmain:
mut a := chan.Chan {} as chan.Chan<i64>
mut b := chan.Chan {} as chan.Chan<i64>
a.Init(2asi64)
b.Init(2asi64)
mut all := Vector {} asVector<chan.Chan<i64>>
all.Push(a)
all.Push(b)
p := pool.New(1asi64, 2asi64)
pool.Submit(p, (): b.Send(42asi64) end)
mut v := 0asi64println chan.Select(all, v, 1000asi64)
println v
println chan.Select(all, v, 10asi64)
a.Close()
b.Close()
println chan.Select(all, v, 10asi64)
pool.Stop(p)
a.Free()
b.Free()
end
Sends the value to the first channel of the vector that has room, without polling, and returns its index. Returns minus one on timeout and minus two when every channel is closed. It works on buffered channels; an unbuffered channel never has room for try_send.
The example for this item is shown with the ones above: chan-API.salam