with_lock
fn with_lock<A, B>(Mutex m, A -> (A, B) f) -> Result<B, ThreadError> Import
Source: use thread::{with_lock}; compiler/src/builtin_docs/thread.hy Locks m, runs f on its value, stores the new value and returns the result.
f gets the current value and returns a pair (new_value, result): the
mutex keeps new_value and with_lock returns Ok(result). The lock is
held for the whole callback, so the update is atomic. If the mutex is
held, it waits (inside a task::scope, only this task waits). This is the
safe way to use a Mutex; prefer it over lock / unlock.
Parameters#
| Name | Type |
|---|---|
m | Mutex |
f | A -> (A, B) |
Returns#
Result<B, ThreadError>
Examples#
use thread::{mutex, with_lock};
use tests::assert;
let m = match mutex(10) {
Result::Ok(m) => m,
Result::Err(_) => panic "mutex failed",
};
let before = match with_lock(m, fn (int n) => (n * 2, n)) {
Result::Ok(old) => old,
Result::Err(_) => -1,
};
assert!(before == 10);
assert!(match with_lock(m, fn (int n) => (n, n)) { Result::Ok(n) => n == 20, Result::Err(_) => false });
See also#
task::scopethread::Mutexthread::lockthread::unlockspawn: Runsf(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.