1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved.
// See the LICENSE file at the top-level directory of this distribution.

use futures::{Async, Future, Poll};
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic;
use std::sync::mpsc as std_mpsc;

use super::{FiberState, Spawn};
use fiber::{self, Task};
use io::poll;

static mut NEXT_SCHEDULER_ID: atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;

thread_local! {
    static CURRENT_CONTEXT: RefCell<InnerContext> = {
        RefCell::new(InnerContext::new())
    };
}

type RequestSender = std_mpsc::Sender<Request>;
type RequestReceiver = std_mpsc::Receiver<Request>;

/// The identifier of a scheduler.
pub type SchedulerId = usize;

/// Scheduler of spawned fibers.
///
/// Scheduler manages spawned fibers state.
/// If a fiber is in runnable state (e.g., not waiting for I/O events),
/// the scheduler will push the fiber in it's run queue.
/// When `run_once` method is called, the first fiber (i.e., future) in the queue
/// will be poped and executed (i.e., `Future::poll` method is called).
/// If the future of a fiber moves to readied state,
/// it will be removed from the scheduler.

/// For efficiency reasons, it is recommended to run a scheduler on a dedicated thread.
#[derive(Debug)]
pub struct Scheduler {
    scheduler_id: SchedulerId,
    next_fiber_id: fiber::FiberId,
    fibers: HashMap<fiber::FiberId, fiber::FiberState>,
    run_queue: VecDeque<fiber::FiberId>,
    request_tx: RequestSender,
    request_rx: RequestReceiver,
    poller: poll::PollerHandle,
}
impl Scheduler {
    /// Creates a new scheduler instance.
    pub fn new(poller: poll::PollerHandle) -> Self {
        let (request_tx, request_rx) = std_mpsc::channel();
        Scheduler {
            scheduler_id: unsafe { NEXT_SCHEDULER_ID.fetch_add(1, atomic::Ordering::SeqCst) },
            next_fiber_id: 0,
            fibers: HashMap::new(),
            run_queue: VecDeque::new(),
            request_tx,
            request_rx,
            poller,
        }
    }

    /// Returns the identifier of this scheduler.
    pub fn scheduler_id(&self) -> SchedulerId {
        self.scheduler_id
    }

    /// Returns the length of the run queue of this scheduler.
    pub fn run_queue_len(&self) -> usize {
        self.run_queue.len()
    }

    /// Returns the count of alive fibers (i.e., not readied futures) in this scheduler.
    pub fn fiber_count(&self) -> usize {
        self.fibers.len()
    }

    /// Returns a handle of this scheduler.
    pub fn handle(&self) -> SchedulerHandle {
        SchedulerHandle {
            request_tx: self.request_tx.clone(),
        }
    }

    /// Runs one unit of works.
    pub fn run_once(&mut self, block_if_idle: bool) {
        let mut did_something = false;
        loop {
            // Request
            match self.request_rx.try_recv() {
                Err(std_mpsc::TryRecvError::Empty) => {}
                Err(std_mpsc::TryRecvError::Disconnected) => unreachable!(),
                Ok(request) => {
                    did_something = true;
                    self.handle_request(request);
                }
            }

            // Task
            if let Some(fiber_id) = self.next_runnable() {
                did_something = true;
                self.run_fiber(fiber_id);
            }

            if !block_if_idle || did_something {
                break;
            }

            let request = self.request_rx.recv().expect("must succeed");
            did_something = true;
            self.handle_request(request);
        }
    }

    fn handle_request(&mut self, request: Request) {
        match request {
            Request::Spawn(task) => self.spawn_fiber(task),
            Request::WakeUp(fiber_id) => {
                if self.fibers.contains_key(&fiber_id) {
                    self.schedule(fiber_id);
                }
            }
        }
    }
    fn spawn_fiber(&mut self, task: Task) {
        let fiber_id = self.next_fiber_id();
        self.fibers
            .insert(fiber_id, fiber::FiberState::new(fiber_id, task));
        self.schedule(fiber_id);
    }
    fn run_fiber(&mut self, fiber_id: fiber::FiberId) {
        let finished;
        let is_runnable = {
            CURRENT_CONTEXT.with(|context| {
                let mut context = context.borrow_mut();
                if context
                    .scheduler
                    .as_ref()
                    .map_or(true, |s| s.id != self.scheduler_id)
                {
                    context.switch(self);
                }
                {
                    let scheduler = assert_some!(context.scheduler.as_mut());
                    if !scheduler.poller.is_alive() {
                        // TODO: Return `Err(io::Error)` to caller and
                        // handle the error in upper layers
                        panic!("Poller is down");
                    }
                }
                assert!(context.fiber.is_none(), "Nested schedulers");
                let fiber = assert_some!(self.fibers.get_mut(&fiber_id));
                context.fiber = Some(fiber as _);
            });
            let fiber = assert_some!(self.fibers.get_mut(&fiber_id));
            finished = fiber.run_once();
            CURRENT_CONTEXT.with(|context| {
                context.borrow_mut().fiber = None;
            });
            fiber.is_runnable()
        };
        if finished {
            self.fibers.remove(&fiber_id);
        } else if is_runnable {
            self.schedule(fiber_id);
        }
    }
    fn next_fiber_id(&mut self) -> fiber::FiberId {
        loop {
            let id = self.next_fiber_id;
            self.next_fiber_id = id.wrapping_add(1);
            if !self.fibers.contains_key(&id) {
                return id;
            }
        }
    }
    fn schedule(&mut self, fiber_id: fiber::FiberId) {
        let fiber = assert_some!(self.fibers.get_mut(&fiber_id));
        if !fiber.in_run_queue {
            self.run_queue.push_back(fiber_id);
            fiber.in_run_queue = true;
        }
    }
    fn next_runnable(&mut self) -> Option<fiber::FiberId> {
        while let Some(fiber_id) = self.run_queue.pop_front() {
            if let Some(fiber) = self.fibers.get_mut(&fiber_id) {
                fiber.in_run_queue = false;
                return Some(fiber_id);
            }
        }
        None
    }
}

/// A handle of a scheduler.
#[derive(Debug, Clone)]
pub struct SchedulerHandle {
    request_tx: RequestSender,
}
impl SchedulerHandle {
    /// Wakes up a specified fiber in the scheduler.
    ///
    /// This forces the fiber to be pushed to the run queue of the scheduler.
    pub fn wakeup(&self, fiber_id: fiber::FiberId) {
        let _ = self.request_tx.send(Request::WakeUp(fiber_id));
    }
}
impl Spawn for SchedulerHandle {
    fn spawn_boxed(&self, fiber: Box<Future<Item = (), Error = ()> + Send>) {
        let _ = self.request_tx.send(Request::Spawn(Task(fiber)));
    }
}

#[derive(Debug)]
pub struct CurrentScheduler {
    pub id: SchedulerId,
    pub handle: SchedulerHandle,
    pub poller: poll::PollerHandle,
}

/// Calls `f` with the current execution context.
///
/// If this function is called on the outside of a fiber, it will ignores `f` and returns `None`.
pub fn with_current_context<F, T>(f: F) -> Option<T>
where
    F: FnOnce(Context) -> T,
{
    CURRENT_CONTEXT.with(|inner_context| inner_context.borrow_mut().as_context().map(f))
}

/// The execution context of the currently running fiber.
#[derive(Debug)]
pub struct Context<'a> {
    scheduler: &'a mut CurrentScheduler,
    fiber: &'a mut FiberState,
}
impl<'a> Context<'a> {
    /// Returns the identifier of the current exeuction context.
    pub fn context_id(&self) -> super::ContextId {
        (self.scheduler.id, self.fiber.fiber_id)
    }

    /// Parks the current fiber.
    pub fn park(&mut self) -> super::Unpark {
        self.fiber
            .park(self.scheduler.id, self.scheduler.handle.clone())
    }

    /// Returns the I/O event poller for this context.
    pub fn poller(&mut self) -> &mut poll::PollerHandle {
        &mut self.scheduler.poller
    }
}

/// Cooperatively gives up a poll for the current future (fiber).
///
/// # Examples
///
/// ```
/// # extern crate fibers;
/// # extern crate futures;
/// use fibers::{fiber, Executor, InPlaceExecutor, Spawn};
/// use futures::{Future, Async, Poll};
///
/// struct HeavyCalculation {
///     polled_count: usize,
///     loops: usize
/// }
/// impl HeavyCalculation {
///     fn new(loop_count: usize) -> Self {
///         HeavyCalculation { polled_count: 0, loops: loop_count }
///     }
/// }
/// impl Future for HeavyCalculation {
///     type Item = usize;
///     type Error = ();
///     fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
///         self.polled_count += 1;
///
///         let mut per_poll_loop_limit = 10;
///         while self.loops > 0 {
///             self.loops -= 1;
///             per_poll_loop_limit -= 1;
///             if per_poll_loop_limit == 0 {
///                 // Suspends calculation and gives execution to other fibers.
///                 return fiber::yield_poll();
///             }
///         }
///         Ok(Async::Ready(self.polled_count))
///     }
/// }
///
/// # fn main() {
/// let mut executor = InPlaceExecutor::new().unwrap();
/// let monitor = executor.spawn_monitor(HeavyCalculation::new(100));
/// let result = executor.run_fiber(monitor).unwrap();
/// assert_eq!(result, Ok(11));
/// # }
/// ```
pub fn yield_poll<T, E>() -> Poll<T, E> {
    with_current_context(|context| context.fiber.yield_once());
    Ok(Async::NotReady)
}

// TODO: rename
#[derive(Debug)]
struct InnerContext {
    pub scheduler: Option<CurrentScheduler>,
    fiber: Option<*mut FiberState>,
}
impl InnerContext {
    fn new() -> Self {
        InnerContext {
            scheduler: None,
            fiber: None,
        }
    }
    pub fn switch(&mut self, scheduler: &Scheduler) {
        self.scheduler = Some(CurrentScheduler {
            id: scheduler.scheduler_id,
            handle: scheduler.handle(),
            poller: scheduler.poller.clone(),
        })
    }
    pub fn as_context(&mut self) -> Option<Context> {
        if let Some(scheduler) = self.scheduler.as_mut() {
            if let Some(fiber) = self.fiber {
                let fiber = unsafe { &mut *fiber };
                return Some(Context { scheduler, fiber });
            }
        }
        None
    }
}

#[derive(Debug)]
enum Request {
    Spawn(Task),
    WakeUp(fiber::FiberId),
}