Line data Source code
1 : use std::{collections::VecDeque, sync::Arc};
2 :
3 : use parking_lot::{Mutex, MutexGuard};
4 :
5 : use crate::executor::{self, PollSome, Waker};
6 :
7 : /// FIFO channel with blocking send and receive. Can be cloned and shared between threads.
8 : /// Blocking functions should be used only from threads that are managed by the executor.
9 : pub struct Chan<T> {
10 : shared: Arc<State<T>>,
11 : }
12 :
13 : impl<T> Clone for Chan<T> {
14 635938 : fn clone(&self) -> Self {
15 635938 : Chan {
16 635938 : shared: self.shared.clone(),
17 635938 : }
18 635938 : }
19 : }
20 :
21 : impl<T> Default for Chan<T> {
22 0 : fn default() -> Self {
23 0 : Self::new()
24 0 : }
25 : }
26 :
27 : impl<T> Chan<T> {
28 80962 : pub fn new() -> Chan<T> {
29 80962 : Chan {
30 80962 : shared: Arc::new(State {
31 80962 : queue: Mutex::new(VecDeque::new()),
32 80962 : waker: Waker::new(),
33 80962 : }),
34 80962 : }
35 80962 : }
36 :
37 : /// Get a message from the front of the queue, block if the queue is empty.
38 : /// If not called from the executor thread, it can block forever.
39 1355 : pub fn recv(&self) -> T {
40 1355 : self.shared.recv()
41 1355 : }
42 :
43 : /// Panic if the queue is empty.
44 68276 : pub fn must_recv(&self) -> T {
45 68276 : self.shared
46 68276 : .try_recv()
47 68276 : .expect("message should've been ready")
48 68276 : }
49 :
50 : /// Get a message from the front of the queue, return None if the queue is empty.
51 : /// Never blocks.
52 60772 : pub fn try_recv(&self) -> Option<T> {
53 60772 : self.shared.try_recv()
54 60772 : }
55 :
56 : /// Send a message to the back of the queue.
57 124944 : pub fn send(&self, t: T) {
58 124944 : self.shared.send(t);
59 124944 : }
60 : }
61 :
62 : struct State<T> {
63 : queue: Mutex<VecDeque<T>>,
64 : waker: Waker,
65 : }
66 :
67 : impl<T> State<T> {
68 124944 : fn send(&self, t: T) {
69 124944 : self.queue.lock().push_back(t);
70 124944 : self.waker.wake_all();
71 124944 : }
72 :
73 129048 : fn try_recv(&self) -> Option<T> {
74 129048 : let mut q = self.queue.lock();
75 129048 : q.pop_front()
76 129048 : }
77 :
78 1355 : fn recv(&self) -> T {
79 1355 : // interrupt the receiver to prevent consuming everything at once
80 1355 : executor::yield_me(0);
81 1355 :
82 1355 : let mut queue = self.queue.lock();
83 1355 : if let Some(t) = queue.pop_front() {
84 0 : return t;
85 1355 : }
86 : loop {
87 2951 : self.waker.wake_me_later();
88 2951 : if let Some(t) = queue.pop_front() {
89 1276 : return t;
90 1596 : }
91 1596 : MutexGuard::unlocked(&mut queue, || {
92 1596 : executor::yield_me(-1);
93 1596 : });
94 : }
95 1276 : }
96 : }
97 :
98 : impl<T> PollSome for Chan<T> {
99 : /// Schedules a wakeup for the current thread.
100 834158 : fn wake_me(&self) {
101 834158 : self.shared.waker.wake_me_later();
102 834158 : }
103 :
104 : /// Checks if chan has any pending messages.
105 670537 : fn has_some(&self) -> bool {
106 670537 : !self.shared.queue.lock().is_empty()
107 670537 : }
108 : }
|