Thread v0.1.0
Installation
Add Thread to the [Dependencies] table of your package's Rux.toml:
[Dependencies]
Thread = { Namespace = "Rux", Version = "0.1.0" }
Standard packages are declared by hand: the registry does not serve them, so rux add Rux/Thread cannot add them.
Dependencies
Core0.1.0FreeBSD0.1.0 (FreeBSD only)Linux0.1.0 (Linux only)macOS0.1.0 (macOS only)Memory0.1.0Windows0.1.0 (Windows only)
Guide
What it provides
| Module | Covers |
|---|---|
Spawn | Spawn, SpawnWith, ThreadOptions with a stack size, and JoinHandle<R> with Join and Detach |
Current | CurrentId, Yield and AvailableParallelism |
Error | ThreadError, why a thread could not be started |
The module names describe where each declaration comes from; they are not part of an import path.
Example
import Thread::Spawn;
func Square(value: uint64) -> uint64 {
return value * value;
}
func Main() -> int {
var handle = Spawn(Square, 12u64) catch { else => return 1 };
return handle.Join() == 144u64 ? 0 : 2;
}
Design
Rux has no closures, so a thread runs a function on a context value the caller moves to it, and leaves the function's result for whoever joins it. Spawn(entry, context) returns a JoinHandle<R>; Join waits for the thread and returns the result. The context and the result must be Core::Sendable, so neither can be a reference or hold an Rc. Dropping the handle, or calling Detach, lets the thread run on and release itself when it finishes, destroying a result nobody took.
On Linux, FreeBSD and macOS threads are started with the C library's pthread_create, which gives each one its stack and its thread-local block, so a program that starts threads is linked against the C library. On Windows they are started with CreateThread. Each thread has its own copy of every thread var, starting at its initial value.
A panic on any thread ends the whole process, as it does on the main thread. Sharing data between threads takes an Atomic<T> or a lock from the Sync package; this package only starts and joins them.
Index
Types
| Name | Summary |
|---|---|
ThreadError | Why Spawn could not start a thread. |
ThreadOptions | How a thread is started: its stack size, for now. |
JoinHandle<R> | A started thread, and the result it will leave. |
Functions
| Name | Summary |
|---|---|
CurrentId | The calling thread's system-wide identifier. |
Yield | Offers the processor to another thread that is ready to run, and returns when this one is scheduled again. |
AvailableParallelism | How many threads can usefully run at once: the number of processors online, and at least one. |
Spawn<T, R> | Starts a thread running entry(context) with the system's default stack size. |
SpawnWith<T, R> | Starts a thread running entry(context) as options say. |