thread
Holding and waiting for the threads that spawn creates.
import thread
In Salam you start a function that should run alongside the rest of the program with spawn. It takes a function with no parameters and no result and gives back a number, the thread's handle. join, or thread.Join, waits for that thread to finish.
The thread package wraps that handle in a Thread so you can keep several of them in a vector and wait for all of them at once, and SpawnStack starts a thread with a stack of the size you choose. Threads share the program's globals and heap; for shared data use sync or atomic, to pass values between threads chan, and to spread a loop over every core pool. A thread cannot be stopped from outside; to ask one to finish early, use ctx or an atomic flag it checks.
Split one job across threads
The most common use of threads is to cut a big job into parts and give each part its own thread. Give each thread its own piece of memory to write its answer into, start them all, then wait for all of them with JoinAll. Because no two threads write to the same place, there is nothing to lock. spawn also takes a second argument, a pointer the function receives as its parameter; that is how each thread learns which part is its own.
import thread
import mem
struct Part:
pub first: i64 = 0
pub last: i64 = 0
pub sum: i64 = 0
end
func add range(p: Part*):
mut total := 0 as i64
mut i := p[0].first
until i <= p[0].last:
total += i
i++
end
p[0].sum = total
end
func new part(first: i64, last: i64): Part*:
p := mem.Allocate(sizeof(Part)) as Part*
p[0] = Part { first = first, last = last }
ret p
end
func main:
size := 250 as i64
mut parts := Vector {} as Vector<Part*>
defer parts.Free()
mut group := Vector {} as Vector<thread.Thread>
defer group.Free()
repeat 4 in w:
p := new part((w as i64) * size + 1, (w as i64 + 1) * size)
parts.Push(p)
group = thread.Collect(group, spawn(add range, p))
end
thread.JoinAll(group)
mut total := 0 as i64
each p in parts:
println p[0].first, "to", p[0].last, "=", p[0].sum
total += p[0].sum
mem.Free(p as void*)
end
println "total:", total
endThe parts may finish in any order, but the program reads the answers only after JoinAll and in the order it stored them, so the output is always the same.
Do something else while a thread works
A thread does not have to be part of a group. Start one slow task in the background, carry on with other work on the main thread, and call Join at the point where you need the result. Until Join returns, do not read what the thread is writing.
import thread
mut words := 0
mut lines := 0
func count text():
text := "the quick brown fox\njumps over\nthe lazy dog"
mut reading := false
lines = 1
repeat text.Len() in i:
c := text[i]
if c == '\n':
lines++
end
if c == ' ' or c == '\n':
reading = false
else not reading:
reading = true
words++
end
end
end
func main:
worker := thread.New(spawn(count text))
println "main thread: loading settings"
println "main thread: opening the report"
thread.Join(worker)
println "lines:", lines, "words:", words
endHere only the main thread prints. If both threads printed, the lines could come out in a different order on every run.
Deep recursion on a bigger stack
A thread from spawn gets the system's default stack, which deep recursion can overflow. SpawnStack starts the function on a stack of the size you ask for. The system may refuse a very large stack, so check the thread with Valid and have a plan for the case where it is not.
import thread
mut depth := 0 as i64
func walk(n: i64): i64:
if n == 0:
ret 0
end
ret 1 + walk(n - 1)
end
func deep work(_arg: void*):
depth = walk(300000)
end
func main:
t := thread.SpawnStack(deep work, null, (128 * 1024 * 1024) as u64)
if thread.Valid(t):
thread.Join(t)
else:
println "no big stack, running on this thread"
deep work(null)
end
println "depth reached:", depth
endThe function given to SpawnStack takes a void*, so the same function can also be called directly with null when no thread could be started.
Pitfalls, and which tool to use
- Join every thread you start. A program that returns from
mainwhile threads are still running cuts them off midway. - Globals are shared by every thread. Two threads that change the same variable without a lock give a different answer from run to run.
- Output from several threads interleaves in no fixed order. Collect results and print them from one thread.
- A handle of zero means the thread did not start.
Joinon it does nothing, so checkValidwhen it matters. - Join each thread exactly once. On Linux and macOS
Joinalso frees the handle, so a secondJoinof the same thread uses freed memory and can crash. Collectreturns the vector it was given, grown by one; always assign the result back, as ingroup = thread.Collect(group, spawn(work)).
| You want to | Use |
|---|---|
| Wait for one or a few threads | spawn with thread.Join or JoinAll |
| Run the turns of a loop on all cores | pool.ParallelFor |
| Let threads change shared data | sync.Mutex or atomic.I64 |
| Pass values from one thread to another | chan.Chan |
| Know when many tasks are done without keeping their handles | sync.WaitGroup |
Types
Thread
struct Thread| Name | Type | Description |
|---|---|---|
handle | i64 = 0 | The handle spawn returned; zero means invalid. |
import thread
import sync
mut total := 0
mut lock := sync.Mutex {}
func worker():
repeat 1000:
sync.Lock(lock)
total++
sync.Unlock(lock)
end
end
func main:
lock = sync.NewMutex()
first := thread.New(spawn(worker))
println thread.Valid(first), thread.Handle(first) != 0
mut group := Vector {} as Vector<thread.Thread>
defer group.Free()
repeat 3:
group = thread.Collect(group, spawn(worker))
end
thread.Join(first)
thread.JoinAll(group)
println group.Len(), total
empty := thread.New(0)
println thread.Valid(empty), empty.handle
thread.Join(empty)
sync.Destroy(lock)
endFunctions
New
func New(h: i64): Threadspawn handle in a Thread.The example for this item is shown with the ones above: thread-Join.salam
SpawnStack
func SpawnStack(fn: i64, arg: void*, stack: u64): Threadvoid* and returns nothing. If the system cannot give that stack it returns an invalid handle, so check with Valid.import thread
mut total := 0 as i64
func count(n: i64): i64:
if n <= 0:
ret 0
end
ret 1 + count(n - 1)
end
func work(_arg: void*):
total = count(200000)
end
func main:
stack := (64 * 1024 * 1024) as u64
t := thread.SpawnStack(work, null, stack)
println thread.Valid(t)
thread.Join(t)
println total
endJoin
func Join(t: Thread)The example for this item is shown with the ones above: thread-Join.salam
JoinAll
func JoinAll(threads: Vector<Thread>)The example for this item is shown with the ones above: thread-Join.salam
Valid
func Valid(t: Thread): boolThe example for this item is shown with the ones above: thread-Join.salam
Handle
func Handle(t: Thread): i64The example for this item is shown with the ones above: thread-Join.salam
Collect
func Collect(threads: Vector<Thread>, h: i64): Vector<Thread>The example for this item is shown with the ones above: thread-Join.salam
SetLimit
func SetLimit(n: i64)spawn returns zero when the limit is reached. Zero means no limit. A thread counts as alive until it is joined.import mem
import thread
mut stop := null as i64*
func hold():
until atomic_load(stop) != 0:
continue
end
end
func main:
stop = mem.AllocateZeroed(8 as u64) as i64*
atomic_store(stop, 1 as i64)
thread.SetLimit(2 as i64)
a := spawn(hold)
b := spawn(hold)
c := spawn(hold)
println "live: ", thread.Live()
println "third refused: ", c == 0
atomic_store(stop, 0 as i64)
join(a)
join(b)
join(c)
println "after join: ", thread.Live()
d := spawn(hold)
println "slot free again: ", d != 0
join(d)
thread.SetLimit(0 as i64)
mem.Free(stop as void*)
endLive
func Live(): i64The example for this item is shown with the ones above: thread-Limit.salam