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
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::sync::mpsc::error::SendError;
use tokio::sync::Semaphore;
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (tx, rx) = tokio::sync::mpsc::channel(1);
let semaphore = Arc::new(Semaphore::new(0));
(
Sender {
semaphore: semaphore.clone(),
chan: tx,
},
Receiver {
semaphore,
chan: rx,
needs_permit: false,
},
)
}
#[derive(Debug)]
pub struct Sender<T> {
semaphore: Arc<Semaphore>,
chan: tokio::sync::mpsc::Sender<T>,
}
impl<T> Sender<T> {
pub async fn send(&self, item: T) -> Result<(), SendError<T>> {
let result = self.chan.send(item).await;
if result.is_ok() {
self.semaphore
.acquire()
.await
.expect("semaphore is never closed")
.forget();
}
result
}
}
#[derive(Debug)]
pub struct Receiver<T> {
semaphore: Arc<Semaphore>,
chan: tokio::sync::mpsc::Receiver<T>,
needs_permit: bool,
}
impl<T> Receiver<T> {
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
let resp = self.chan.poll_recv(cx);
if self.needs_permit && matches!(resp, Poll::Pending) {
self.needs_permit = false;
self.semaphore.add_permits(1);
}
if matches!(resp, Poll::Ready(_)) {
self.needs_permit = true;
}
resp
}
}
#[cfg(test)]
mod test {
use crate::future::rendezvous::{channel, Receiver};
use std::sync::{Arc, Mutex};
use tokio::macros::support::poll_fn;
async fn recv<T>(rx: &mut Receiver<T>) -> Option<T> {
poll_fn(|cx| rx.poll_recv(cx)).await
}
#[tokio::test]
async fn send_blocks_caller() {
let (tx, mut rx) = channel::<u8>();
let done = Arc::new(Mutex::new(0));
let idone = done.clone();
let send = tokio::spawn(async move {
*idone.lock().unwrap() = 1;
tx.send(0).await.unwrap();
*idone.lock().unwrap() = 2;
tx.send(1).await.unwrap();
*idone.lock().unwrap() = 3;
});
assert_eq!(*done.lock().unwrap(), 0);
assert_eq!(recv(&mut rx).await, Some(0));
assert_eq!(*done.lock().unwrap(), 1);
assert_eq!(recv(&mut rx).await, Some(1));
assert_eq!(*done.lock().unwrap(), 2);
assert_eq!(recv(&mut rx).await, None);
assert_eq!(*done.lock().unwrap(), 3);
let _ = send.await;
}
#[tokio::test]
async fn send_errors_when_rx_dropped() {
let (tx, rx) = channel::<u8>();
drop(rx);
tx.send(0).await.expect_err("rx half dropped");
}
}