condition_variable
import std::sync::condition_variable; · source
Types
ConditionVariable
type struct ConditionVariable {
private inner: mut ConditionVariableInner*;
}
Atomically release a Mutex and sleep until another thread signals — the standard producer/consumer primitive. A pthread_cond_t on POSIX; on Windows a CONDITION_VARIABLE waited on with the mutex's SRW lock. Use one ConditionVariable with only one Mutex.
import std::alloc::allocator::{ GlobalAllocator };
import std::sync::mutex::{ Mutex, MutexGuard };
import std::sync::condition_variable::{ ConditionVariable };
// `queued` and `cond` are shared with the producer, which raises the count and signals
function wait_for_work(queued: &Mutex<i64>, cond: &ConditionVariable) -> void {
mut guard: MutexGuard<i64, GlobalAllocator> = queued.lock();
while (*guard.as_pointer() == 0) {
cond.wait(queued, &guard);
}
// act on the queue
}
wait(mutex, guard) releases the lock, sleeps, and reacquires before returning. The guard stays "locked" from your perspective; the platform does the unlock and relock internally, and the guard still refers to the same lock. wait_timeout(mutex, guard, duration) waits no longer than duration and answers true when the time ran out, false when the thread was woken.
notify_one() wakes one waiter, notify_all() wakes all. If nothing is waiting, a signal is lost — standard pthread semantics, which is why the consumer must check the predicate before sleeping. Spurious wake-ups are possible regardless, so re-check the predicate after waking; that is why the example loops rather than using an if.
Cryo has no borrow checker, so it is on you not to touch the guarded value while inside
wait()— doing so reads through the guard while another thread holds the lock.
new() panics if the condition variable cannot be made; try_new() returns the AllocationError instead. ConditionVariable is Send + Sync unconditionally.
Constructors
static new() -> ConditionVariable;
static new() -> ConditionVariable;Construct a fresh condition variable with default attributes. Panics on allocation failure or pthread init failure.
static try_new() -> Result<ConditionVariable, AllocationError>;
static try_new() -> Result<ConditionVariable, AllocationError>;Construct a condition variable, or Err when it cannot be made: an OutOfMemory AllocationError both when its storage cannot be allocated and when pthread_cond_init fails (unix; the Windows initialisation cannot fail).
Methods
wait<T, A>(&this, mutex: &Mutex<T, A>, guard: mut &MutexGuard<T, A>) -> void;
wait<T, A>(&this, mutex: &Mutex<T, A>, guard: mut &MutexGuard<T, A>) -> void;Block the current thread until another thread signals this condition variable. Atomically releases mutex, waits, and reacquires mutex before returning. guard is not invalidated - its address still refers to the same MutexInner - but inspect the guarded value only after wait returns.
wait_timeout<T, A>(&this, mutex: &Mutex<T, A>, guard: mut &MutexGuard<T, A>, duration: Duration) -> boolean;
wait_timeout<T, A>(&this, mutex: &Mutex<T, A>, guard: mut &MutexGuard<T, A>, duration: Duration) -> boolean;Wait as wait does, but for no longer than duration. Answers true when the wait ended because duration passed - never before the whole of it has, on the monotonic clock - and false when the thread was woken. A wake can be spurious, as for wait, so check the condition waited for either way.
notify_one(&this) -> void;
notify_one(&this) -> void;Wake up one thread waiting on this condition variable. If no thread is currently waiting, the signal is lost (this is the standard pthread semantics; the producer should arrange for the consumer to check the predicate before sleeping).
notify_all(&this) -> void;
notify_all(&this) -> void;Wake up every thread currently waiting on this condition variable. Spurious wake-ups are possible regardless; the consumer must re-check the predicate after waking.
Trait implementations
implement trait Drop for struct ConditionVariable
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct ConditionVariable {}A condition variable: lets a thread holding a Mutex give up the lock and sleep until another thread calls notify_one or notify_all. A pthread_cond_t on unix; on Windows a CONDITION_VARIABLE waited on with the mutex's SRW lock. Wakes can be spurious, so wait in a loop that re-checks the condition.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
ConditionVariable.inner: mut ConditionVariableInner*mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
type struct GlobalAllocator {}Zero-sized handle to the process-wide allocator. Construct with GlobalAllocator::new(); all instances dispatch through the same underlying backend.
type struct Mutex<T, A = GlobalAllocator> where A: Allocator {}A value of type T that one thread at a time may use. lock waits for the lock and returns a MutexGuard through which the value is read and written; dropping the guard releases the lock. The lock and the value live in one block allocated from A, so the Mutex handle can move while the lock stays put.
type struct MutexGuard<T, A> {}RAII guard returned by Mutex::lock. Carries a raw pointer to the inner so it can release the lock on drop. Read the guarded value through as_pointer(); write it through as_mutable_pointer(), from a guard held writably.
namespace std::sync::condition_variable;ConditionVariable: condition variable for blocking until a predicate holds.
module pagetype struct ConditionVariable {}A condition variable: lets a thread holding a Mutex give up the lock and sleep until another thread calls notify_one or notify_all. A pthread_cond_t on unix; on Windows a CONDITION_VARIABLE waited on with the mutex's SRW lock. Wakes can be spurious, so wait in a loop that re-checks the condition.
function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function wait_for_work(queued: &Mutex<i64>, cond: &ConditionVariable) -> void(parameter) queued: &Mutex<i64>(parameter) cond: &ConditionVariablemut guard: MutexGuard<i64, GlobalAllocator>(parameter) queued: &Mutex<i64>Mutex::lock(&this) -> MutexGuard<T, A>Acquire the lock, blocking the current thread until it is available. Returns a guard whose drop() will release the lock. The lock is not recursive: locking it again from the thread that holds it never returns (a default-attribute pthread mutex and an SRW lock both deadlock).
while (condition) { ... }Repeats its body while the condition holds. The condition is checked before every iteration, so the body may run zero times.
language referencemut guard: MutexGuard<i64, GlobalAllocator>MutexGuard::as_pointer(&this) -> T*Read-only pointer to the guarded value. Valid for the lifetime of this guard; never null.
(parameter) cond: &ConditionVariableConditionVariable::wait<T, A>(&this, mutex: &Mutex<T, A>, guard: mut &MutexGuard<T, A>) -> voidBlock the current thread until another thread signals this condition variable. Atomically releases mutex, waits, and reacquires mutex before returning. guard is not invalidated - its address still refers to the same MutexInner - but inspect the guarded value only after wait returns.
ConditionVariable::wait_timeout<T, A>(&this, mutex: &Mutex<T, A>, guard: mut &MutexGuard<T, A>, duration: Duration) -> booleanWait as wait does, but for no longer than duration. Answers true when the wait ended because duration passed - never before the whole of it has, on the monotonic clock - and false when the thread was woken. A wake can be spurious, as for wait, so check the condition waited for either way.
trueThe boolean literal. Booleans are a distinct 1-byte type, not interchangeable with integers; if and while conditions must be boolean.
falseThe boolean literal. Booleans are a distinct 1-byte type, not interchangeable with integers; if and while conditions must be boolean.
ConditionVariable::notify_one(&this) -> voidWake up one thread waiting on this condition variable. If no thread is currently waiting, the signal is lost (this is the standard pthread semantics; the producer should arrange for the consumer to check the predicate before sleeping).
std::sync::condition_variableConditionVariable::notify_all(&this) -> voidWake up every thread currently waiting on this condition variable. Spurious wake-ups are possible regardless; the consumer must re-check the predicate after waking.
std::sync::condition_variableif (condition) { ... } else if (condition) { ... } else { ... }Branches on a parenthesised boolean condition. Bodies are always braced; there is no single-statement form. Used as an expression, both arms are required and must produce the same type: const sign = if (n < 0) { -1 } else { 1 };.
static ConditionVariable::new() -> ConditionVariableConstruct a fresh condition variable with default attributes. Panics on allocation failure or pthread init failure.
std::sync::condition_variablestatic ConditionVariable::try_new() -> Result<ConditionVariable, AllocationError>Construct a condition variable, or Err when it cannot be made: an OutOfMemory AllocationError both when its storage cannot be allocated and when pthread_cond_init fails (unix; the Windows initialisation cannot fail).
type struct AllocationError {
kind: AllocationErrorKind;
layout: Layout;
}The error an Allocator returns: what went wrong (kind) and the layout that was requested when it did (layout; for a reallocate, the new layout).
type trait Send {}Types that are safe to transfer between threads. An owning value of a Send type may cross a thread boundary without violating memory safety.
type trait Sync {}Types that are safe to share between threads by shared reference. T: Sync if &T: Send.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
Result::Err(E)AllocationErrorKind::OutOfMemoryThe underlying allocator returned null; the system is out of memory or hit an address-space limit.
std::alloc::allocator&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
(parameter) mutex: &Mutex<T, A>(parameter) guard: mut &MutexGuard<T, A>mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
(parameter) duration: Durationtype struct Duration with [Eq, Ord, Debug] {
const NANOSECONDS_PER_SECOND: u64 = 1000000000;
const NANOSECONDS_PER_MILLISECOND: u64 = 1000000;
const NANOSECONDS_PER_MICROSECOND: u64 = 1000;
const MILLISECONDS_PER_SECOND: u64 = 1000;
const MICROSECONDS_PER_SECOND: u64 = 1000000;
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 3600;
const SECONDS_PER_DAY: u64 = 86400;
}A length of time: whole secs plus a sub-second nanos remainder (0 <= nanos < 1_000_000_000). POD; copy-by-value, no drop. Ordered by seconds, then nanoseconds.
implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referencetype trait Drop {
drop(mut &this) -> void;
}A type that releases something when a value of it ends: memory, a file handle, a lock. The compiler calls drop once when an owned value goes out of scope; release a value early with mem::drop(value).
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language reference