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