1 use loom::sync::Notify;
2
3 use std::sync::{Arc, Mutex};
4
channel<T>() -> (Sender<T>, Receiver<T>)5 pub(crate) fn channel<T>() -> (Sender<T>, Receiver<T>) {
6 let inner = Arc::new(Inner {
7 notify: Notify::new(),
8 value: Mutex::new(None),
9 });
10
11 let tx = Sender {
12 inner: inner.clone(),
13 };
14 let rx = Receiver { inner };
15
16 (tx, rx)
17 }
18
19 pub(crate) struct Sender<T> {
20 inner: Arc<Inner<T>>,
21 }
22
23 pub(crate) struct Receiver<T> {
24 inner: Arc<Inner<T>>,
25 }
26
27 struct Inner<T> {
28 notify: Notify,
29 value: Mutex<Option<T>>,
30 }
31
32 impl<T> Sender<T> {
send(self, value: T)33 pub(crate) fn send(self, value: T) {
34 *self.inner.value.lock().unwrap() = Some(value);
35 self.inner.notify.notify();
36 }
37 }
38
39 impl<T> Receiver<T> {
recv(self) -> T40 pub(crate) fn recv(self) -> T {
41 loop {
42 if let Some(v) = self.inner.value.lock().unwrap().take() {
43 return v;
44 }
45
46 self.inner.notify.wait();
47 }
48 }
49 }
50