std.thread
Code that runs at the same time: the threads of the system (Thread), lightweight tasks that share a few threads (Task and Group), and what they use together: Mutex for data that change, Shared for a value that the handlers of the windows change too, Channel to pass values and Atomic for counters.
The compiler checks what a thread or a task captures: while it runs, the code that started it cannot change what it reads, nor touch what it changes. Data that several of them change go in a Mutex.
import std.thread
thread.Atomic<i64> done
thread.Group jobs
for (i64 i = 0; i < 100; i++) {
jobs.start([done]() { done.add(1) })
}
jobs.wait()
println("{}", done.load()) // 100The guide: Threads, tasks and channels.
Made from the documentation in the sources of the library.
#Types
#Thread
struct ThreadA thread of the system, made from a lambda, started with start() and waited for with join(). An exception that ends the thread is thrown again by join(); one that no join() takes stops the program.
A thread whose lambda captures by address, with ref or by reading a value that is not simple, belongs to its block: if join() was not called, the block waits for the thread at its end. A thread that owns all that it uses, with move or simple values, can outlive the block, as in a list.
i64 total = 0
thread.Thread worker = thread.Thread([ref total]() { total = 42 })
worker.start()
worker.join()Thread(move func() work)A thread that will run work, which is moved into it; it starts with start().
#Thread.start
void start()Starts the thread. Starting it a second time is a panic.
#Thread.join
void join()Waits for the end of the thread, and throws again the exception that ended it, if any. A panic if the thread is not started or is already joined.
#Thread.detach
void detach()Lets the thread go on by itself, as std::thread::detach of C++: its destructor no longer waits for it, nobody joins it, and the end of main does not wait for it; an exception that ends it stops the program. Only a thread that owns all that it uses can be detached: the compiler refuses one that captures by address, which belongs to its block. A panic if the thread is not started, or is already joined or detached.
thread.Thread worker = thread.Thread([progress]() { slowWork(progress) })
worker.start()
worker.detach()#Task
struct TaskA lightweight task, with the interface and the rules of Thread: the runtime runs many tasks on a few threads of the system, one for each processor, and a task costs a few kilobytes. A task that waits, for the network, for time.sleep(), for a mutex, for a channel or for join(), leaves its thread to the other tasks. A task that blocks its thread, as in a C function, keeps it, and after about a millisecond the runtime gives the other tasks another thread.
Use tasks for work that waits, as servers and clients of the network, and threads for long computations.
Task(move func() work)A task that will run work, which is moved into it; it starts with start().
#Task.start
void start()Starts the task. Starting it a second time is a panic.
#Task.join
void join()Waits for the end of the task, and throws again the exception that ended it, if any. A panic if the task is not started or is already joined.
#Task.detach
void detach()Lets the task go on by itself, as detach() of Thread: its destructor no longer waits for it, nobody joins it, and the end of main does not wait for it; an exception that ends it stops the program. The compiler refuses it for a task that captures by address. A panic if the task is not started, or is already joined or detached.
#Group
struct GroupTasks started one by one, also in a loop, and waited for together. The tasks can read the variables declared before the group, which stay constant until the end of its block, and take others with move; they cannot capture with ref. At the end of its block the group waits for all its tasks, and an exception that no wait() took stops the program.
#Group.start
void start(move func() work)Starts a task of the group that runs work, which is moved into it.
#Group.wait
void wait()Waits for the tasks started so far, and throws again the first exception of one of them; the others are lost.
#Mutex
struct Mutex<T>Data that threads and tasks share and change, which start with the default value of T. They are reached only inside lock(), by one at a time, so a lock cannot be forgotten.
#Mutex.lock
void lock(func(ref T) body) constLocks the mutex, calls body with the data by ref, and unlocks it at the end of body, also when an exception goes through. Who finds it locked waits; a task leaves its thread to the others meanwhile. Locking the same mutex again inside body waits for ever.
thread.Mutex<i64> counter
counter.lock([](ref i64 n) { n++ })#Shared
struct Shared<T>A value that the handlers of the windows, the threads and the tasks change: a handle to the value with its lock, which stays until the end of the program. A handle is a simple value, copied freely: every copy reaches the same value, and a lambda that is kept, as a handler of a window, captures it by copy, where a Mutex could not go. The value is reached only inside lock, by one at a time.
thread.Shared<i64> clicks = thread.Shared<i64>(0)
button.onClick([clicks, label]() {
clicks.lock([label](ref i64 n) {
n++
label.setText(format("{} clicks", n))
})
})Shared(move T value)Keeps the value, moved here, for the whole program.
#Shared.lock
void lock(func(ref T) body) constLocks the value, calls body with it by ref, and unlocks it at the end of body, also when an exception goes through. Who finds it locked waits; a task leaves its thread to the others meanwhile. Locking it again inside body waits for ever. A Shared declared without a value has none: locking it is a panic.
#Channel
struct Channel<T>Values passed from task to task and from thread to thread, in the order they are sent. It holds up to a capacity of values, given to its constructor; with capacity 0, the default, the sender waits until a receiver has the value. close() ends it, and for (T v in channel) receives until then. The values still in the channel when it is destroyed are destroyed with it.
thread.Channel<string> lines = thread.Channel<string>(16)
thread.Task reader = thread.Task([lines]() {
for (string line in lines) {
println("{}", line)
}
})
reader.start()
lines.send("hello")
lines.close()
reader.join()Channel(i64 count)A channel that holds up to count values before send() waits; with 0, the sender waits until a receiver has the value. A negative count is a panic.
#Channel.send
void send(move T value) constSends the value, which is moved into the channel, and waits while the channel is full. Throws if the channel is closed; the value is then destroyed.
#Channel.receive
T receive() constThe next value, in the order they were sent; waits while the channel is empty. Throws once the channel is closed and empty.
#Channel.next
bool next(ref T value) constAs receive(), but without the exception: puts the next value in value and gives true, or gives false, with value unchanged, once the channel is closed and empty. It is the step of for (T v in channel).
#Channel.close
void close() constCloses the channel: from then on send() throws, while the values already sent can still be received; after them receive() throws and the loops on the channel end. A second close() does nothing.
#Atomic
struct Atomic<T>An integer or a bool that threads and tasks read and change together without a lock. Each operation happens whole, and all of them in one order that every thread sees, the sequential consistency. An atomic cannot be copied: the threads and the tasks capture it by reading it.
Atomic(move T initial)An atomic with the value initial; one declared without a value starts with 0 or false.
#Atomic.load
T load() constThe value.
#Atomic.store
void store(T value) constWrites the value.
#Atomic.add
T add(T amount) constAdds amount, and gives the value before; for an integer only.
#Atomic.loadRelaxed
T loadRelaxed() constThe value, without an order among the threads: what the others wrote before may not be seen yet, but the value itself is never half written. For counters and statistics, where only the value counts.
#Atomic.storeRelaxed
void storeRelaxed(T value) constWrites the value, without an order among the threads.
#Atomic.addRelaxed
T addRelaxed(T amount) constAdds amount without an order among the threads, and gives the value before; for an integer only. A counter that many threads increase.
#Atomic.exchange
T exchange(T value) constWrites the value, and gives the one before.
#Atomic.compareExchange
bool compareExchange(T expected, T desired) constWrites desired only if the value is expected, in one step: true if it did.