fibers/sync/
mod.rs

1// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved.
2// See the LICENSE file at the top-level directory of this distribution.
3
4//! Synchronization primitives.
5use std::sync::Arc;
6
7use fiber;
8use sync_atomic::AtomicCell;
9
10pub mod mpsc;
11pub mod oneshot;
12
13#[derive(Debug, Clone)]
14struct Notifier {
15    unpark: Arc<AtomicCell<Option<fiber::Unpark>>>,
16}
17impl Notifier {
18    pub fn new() -> Self {
19        Notifier {
20            unpark: Arc::new(AtomicCell::new(None)),
21        }
22    }
23    pub fn await(&mut self) {
24        loop {
25            if let Some(mut unpark) = self.unpark.try_borrow_mut() {
26                let context_id = fiber::with_current_context(|c| c.context_id());
27                if unpark.as_ref().map(|u| u.context_id()) != context_id {
28                    *unpark = fiber::with_current_context(|mut c| c.park());
29                }
30                return;
31            }
32        }
33    }
34    pub fn notify(&self) {
35        loop {
36            if let Some(mut unpark) = self.unpark.try_borrow_mut() {
37                *unpark = None;
38                return;
39            }
40        }
41    }
42}