Thread v0.1.0

Source
Threads of execution: starting, joining and detaching them, and asking about the current one

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

Guide

What it provides

ModuleCovers
SpawnSpawn, SpawnWith, ThreadOptions with a stack size, and JoinHandle<R> with Join and Detach
CurrentCurrentId, Yield and AvailableParallelism
ErrorThreadError, 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

NameSummary
ThreadErrorWhy Spawn could not start a thread.
ThreadOptionsHow a thread is started: its stack size, for now.
JoinHandle<R>A started thread, and the result it will leave.

Functions

NameSummary
CurrentIdThe calling thread's system-wide identifier.
YieldOffers the processor to another thread that is ready to run, and returns when this one is scheduled again.
AvailableParallelismHow 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.