text

source of std::sync

1// What tasks share (LANGUAGE_SPEC.md section 5.6).2//3// The types here declare Shared, a lang item: their fields change through4// a `'&'`, since each synchronizes its own changes, and the compiler lets5// every task of a scope use them. Atomic values, a mutex whose guard is6// disposed to unlock it, and a channel moving values from task to task.7// The externs are the runtime's atomic operations and futex waits (the8// interpreter runs them over its cooperative tasks).910import std::option;11import std::dispose;12import std::vector;1314// Values whose changes synchronize themselves, which any task may use.15exp interface Shared {}1617// What an Atomic holds: the integer types and bool, which satisfy it18// with no marker (a lang item).19exp interface AtomicValue {}2021extern al_atomic_load(at: &[u8], size: u64) -> u64;22extern al_atomic_store(at: &var [u8], size: u64, bits: u64);23extern al_atomic_exchange(at: &var [u8], size: u64, bits: u64) -> u64;24extern al_atomic_compare_exchange(at: &var [u8], size: u64, expected: u64, desired: u64) -> u64;25extern al_atomic_add(at: &var [u8], size: u64, bits: u64) -> u64;26extern al_wait(at: &[u8], expected: u32);27extern al_wake(at: &[u8], count: u32);2829const EVERY_WAITER: u32 = 0xFFFFFFFF; // al_wake's count waking all3031/* --- Atomic values --- */3233// An integer or bool read and changed whole, each operation sequentially34// consistent.35exp type Atomic<T: AtomicValue> : Shared = struct {36    cell: [T : 1]37};3839exp fn Atomic::from(value: T) -> Atomic<T> {40    return Atomic<T> { .cell = [move value] };41}4243exp fn load<T: AtomicValue>(self a: &Atomic<T>) -> T {44    return from_bits<T>(al_atomic_load(&a.cell[..] as &[u8], T.size()));45}4647exp fn store<T: AtomicValue>(self a: &Atomic<T>, value: T) {48    al_atomic_store(&var a.cell[..] as &var [u8], T.size(), bits_of(copy value));49}5051// Stores the value and gives the one before.52exp fn exchange<T: AtomicValue>(self a: &Atomic<T>, value: T) -> T {53    return from_bits<T>(al_atomic_exchange(54        &var a.cell[..] as &var [u8],55        T.size(),56        bits_of(copy value)57    ));58}5960// Stores desired if the value is expected, and says whether it was.61exp fn compare_exchange<T: AtomicValue>(self a: &Atomic<T>, expected: T, desired: T) -> bool {62    const wanted = bits_of(copy expected);63    return al_atomic_compare_exchange(64        &var a.cell[..] as &var [u8],65        T.size(),66        wanted,67        bits_of(copy desired)68    ) == wanted;69}7071// Adds the amount, wrapping, and gives the value before.72exp fn add(self a: &Atomic<u8>, amount: u8) -> u8 {73    return a.add_bits(amount);74}7576exp fn add(self a: &Atomic<u16>, amount: u16) -> u16 {77    return a.add_bits(amount);78}7980exp fn add(self a: &Atomic<u32>, amount: u32) -> u32 {81    return a.add_bits(amount);82}8384exp fn add(self a: &Atomic<u64>, amount: u64) -> u64 {85    return a.add_bits(amount);86}8788exp fn add(self a: &Atomic<i8>, amount: i8) -> i8 {89    return a.add_bits(amount);90}9192exp fn add(self a: &Atomic<i16>, amount: i16) -> i16 {93    return a.add_bits(amount);94}9596exp fn add(self a: &Atomic<i32>, amount: i32) -> i32 {97    return a.add_bits(amount);98}99100exp fn add(self a: &Atomic<i64>, amount: i64) -> i64 {101    return a.add_bits(amount);102}103104fn add_bits<T: AtomicValue>(self a: &Atomic<T>, amount: T) -> T {105    return from_bits<T>(al_atomic_add(106        &var a.cell[..] as &var [u8],107        T.size(),108        bits_of(copy amount)109    ));110}111112// The value's bytes in the low bytes of a u64.113fn bits_of<T>(value: T) -> u64 {114    var raw: [u64 : 1] = [0];115    (&var raw[..] as &var [T])[0] = move value;116    return raw[0];117}118119fn from_bits<T>(bits: u64) -> T {120    const raw: [u64 : 1] = [bits];121    return copy (&raw[..] as &[T])[0];122}123124/* --- Mutex --- */125126// A value one task at a time reaches, through the guard `lock` gives.127// A mutex of a disposable value is disposable, disposing the value.128exp type Mutex<T> : Shared + Disposable if (T: Disposable) = struct {129    state: Atomic<u32>, // a lock state, the word tasks wait on130    value: T131};132133// The lock states.134const FREE: u32 = 0;135const LOCKED: u32 = 1;136const WAITED_ON: u32 = 2; // locked with tasks waiting137138exp fn Mutex::from(value: T) -> Mutex<T> {139    return Mutex<T> { .state = Atomic<u32>::from(FREE), .value = move value };140}141142exp fn dispose<T: Disposable>(self m: &var Mutex<T>) {143    m.value.dispose();144}145146// The mutex locked until the guard is disposed.147exp type Guard<T> : Disposable = struct {148    mutex: &Mutex<T>149};150151// Waits until the mutex is free and locks it.152exp fn lock<T>(self m: &Mutex<T>) -> Guard<T> {153    lock_state(&m.state);154    return Guard<T> { .mutex = &m };155}156157// The locked value.158exp fn value<T>(self g: &Guard<T>) -> &var T {159    return &var g.mutex.value;160}161162// Unlocks the mutex.163exp fn dispose<T>(self g: &var Guard<T>) {164    unlock_state(&g.mutex.state);165}166167fn lock_state(state: &Atomic<u32>) {168    if (state.compare_exchange(FREE, LOCKED)) {169        return;170    }171    while (state.exchange(WAITED_ON) != FREE) {172        al_wait(&state.cell[..] as &[u8], WAITED_ON);173    }174}175176fn unlock_state(state: &Atomic<u32>) {177    if (state.exchange(FREE) == WAITED_ON) {178        al_wake(&state.cell[..] as &[u8], 1);179    }180}181182/* --- Channel --- */183184// Values sent by some tasks and received by others, first in first out.185// A channel of disposable values is disposable, disposing those still186// queued.187exp type Channel<T> : Shared + Disposable if (T: Disposable) = struct {188    state: Atomic<u32>, // locks the queue, as a Mutex's state189    signal: Atomic<u32>, // changes with every send and the close190    sent: Vector<T>, // newest last191    next: Vector<T>, // oldest last, taken first192    closed: bool193};194195exp fn Channel::empty() -> Channel<T> {196    return Channel<T> {197        .state = Atomic<u32>::from(FREE),198        .signal = Atomic<u32>::from(0),199        .sent = Vector<T>::empty(),200        .next = Vector<T>::empty(),201        .closed = false202    };203}204205// Queues the item for a receiver.206exp fn send<T>(self c: &Channel<T>, item: T) {207    lock_state(&c.state);208    c.sent.push(move item);209    unlock_state(&c.state);210    c.signal.add(1);211    al_wake(&c.signal.cell[..] as &[u8], 1);212}213214// The oldest item not yet received, waiting for one; None once the215// channel is closed and empty.216exp fn receive<T>(self c: &Channel<T>) -> Option<T> {217    while (true) {218        const seen = c.signal.load();219        lock_state(&c.state);220        if (c.take_oldest() is ::Some |move item|) {221            unlock_state(&c.state);222            return ::Some(move item);223        }224        const closed = c.closed;225        unlock_state(&c.state);226        if (closed) {227            return ::None;228        }229        al_wait(&c.signal.cell[..] as &[u8], seen);230    }231}232233// The oldest item not yet received, or None at once when there is none.234exp fn try_receive<T>(self c: &Channel<T>) -> Option<T> {235    lock_state(&c.state);236    var taken = c.take_oldest();237    unlock_state(&c.state);238    return move taken;239}240241// The oldest item queued, with the channel locked.242fn take_oldest<T>(self c: &Channel<T>) -> Option<T> {243    if (c.next.length() == 0) {244        // the sent items, reversed, so that popping takes the oldest245        while (c.sent.pop() is ::Some |move item|) {246            c.next.push(move item);247        }248    }249    return c.next.pop();250}251252// Ends the channel: receivers get what is queued, then None.253exp fn close<T>(self c: &Channel<T>) {254    lock_state(&c.state);255    c.closed = true;256    unlock_state(&c.state);257    c.signal.add(1);258    al_wake(&c.signal.cell[..] as &[u8], EVERY_WAITER);259}260261// Disposes the queued items, oldest first.262exp fn dispose<T: Disposable>(self c: &var Channel<T>) {263    while (c.next.pop() is ::Some |move item|) {264        item.dispose();265    }266    c.next.dispose();267    c.sent.dispose();268}269270/* --- Slices --- */271272// The slice in pieces of at most size elements, each its own `&var [T]`,273// so that tasks may each change one (section 5.6).274exp fn chunks<T>(items: &var [T], size: u64) -> Vector<&var [T]> {275    var pieces = Vector<&var [T]>::empty();276    var start: u64 = 0;277    while (start < items.length()) {278        var end = start + size;279        if (end > items.length() || size == 0) {280            end = items.length();281        }282        pieces.push(&var items[start..end]);283        start = end;284    }285    return move pieces;286}