thread
spawn runs a function on a new OS thread with its own VM and heap. Values
cross between threads by copy through send/recv on a channel or through a
Mutex / RwLock; heap handles such as gc::Root cannot be sent.
For concurrent IO on one thread, tasks are lighter. Threads pay off for CPU-bound work. See the threads tutorial.
Built into the compiler.
Import what you use (use path::* is not allowed):
use thread::{Thread, Sender};
Types#
| Name | Description |
|---|---|
Thread | A handle to a function running on another OS thread, from spawn. |
Sender | The sending half of a channel made by channel. |
Receiver | The receiving half of a channel made by channel. |
Mutex | A mutual-exclusion lock that owns a value, made by mutex. |
RwLock | A readers-writer lock that owns a value, made by rwlock. |
ThreadError | The error of every thread function. |
Functions#
| Name | Description |
|---|---|
spawn | Runs f(arg) on another OS thread and returns a handle to it. |
join | Waits for the thread to finish and returns the value its function returned. |
detach | Lets the thread run to completion without being joined. |
channel | Creates an unbounded channel and returns its (Sender, Receiver) ends. |
send | Sends a copy of value on the channel. |
recv | Takes the next value from the channel, waiting until one arrives. |
try_send | Sends value without waiting. |
try_recv | Takes the next value if there is one, without waiting. |
close | Closes the channel: no more sends. |
mutex | Creates a mutex holding a copy of initial. |
with_lock | Locks m, runs f on its value, stores the new value and returns the result. |
lock | Locks m until unlock, waiting while another thread holds it. |
try_lock | Locks m if it is free, without waiting. |
unlock | Releases a mutex this thread locked with lock or try_lock. |
rwlock | Creates a readers-writer lock holding a copy of initial. |
with_read | Runs f on a snapshot of the lock’s value and returns what f returns. |
with_write | Takes the write lock, runs f and stores the new value it returns. |
try_read | Like with_read, but returns Err(ThreadError::WouldBlock) instead of waiting when a writer holds the lock. |
try_write | Like with_write, but returns Err(ThreadError::WouldBlock) instead of waiting when the lock is held. |