Function in thread compiler

with_lock

fn with_lock<A, B>(Mutex m, A -> (A, B) f) -> Result<B, ThreadError>
Import
use thread::{with_lock};
Source: 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#

NameType
mMutex
fA -> (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#

↑ ↓ navigate ↵ open