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
// goroutine: `go!{...}` → spawn a goroutine.
//
// Go goish
// ───────────────────────────────── ──────────────────────────────────
// go worker(jobs) go!{ worker(jobs); };
// go func() { ... }() go!{ ... };
//
// Implementation note: v0.1 spawns an OS thread (std::thread::spawn), not a
// green thread. Tens of thousands of goroutines won't scale here like they
// do in Go — that's deferred until we have a real scheduler. The `go!{}`
// macro returns a `JoinHandle` so you can .Wait() on it if desired.
use std::thread::JoinHandle;
/// Wrapper around `std::thread::JoinHandle` with Go-style `Wait()`.
pub struct Goroutine {
handle: Option<JoinHandle<()>>,
}
impl Goroutine {
/// Spawn a new goroutine running `f`. Normally users invoke this via
/// `go!{ ... }` rather than calling directly.
pub fn spawn<F>(f: F) -> Goroutine
where
F: FnOnce() + Send + 'static,
{
use std::sync::atomic::Ordering;
crate::runtime::LIVE_GOROUTINES.fetch_add(1, Ordering::SeqCst);
let handle = std::thread::spawn(move || {
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
crate::runtime::LIVE_GOROUTINES.fetch_sub(1, Ordering::SeqCst);
}
}
let _g = Guard;
f();
});
Goroutine { handle: Some(handle) }
}
/// Wait for the goroutine to finish. Returns nil error if it completed
/// normally, or an error if it panicked.
pub fn Wait(mut self) -> crate::errors::error {
match self.handle.take() {
Some(h) => match h.join() {
Ok(()) => crate::errors::nil,
Err(_) => crate::errors::New("goroutine panicked"),
},
None => crate::errors::nil,
}
}
}
/// `go!{ stmts }` — spawn a goroutine running the block.
///
/// Returns a `Goroutine` handle — ignore it if you don't need to wait.
#[macro_export]
macro_rules! go {
($($tt:tt)*) => {
$crate::goroutine::Goroutine::spawn(move || {
$($tt)*
})
};
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
#[test]
fn go_runs_in_another_thread_and_wait_joins() {
let log: Arc<Mutex<Vec<i32>>> = Arc::new(Mutex::new(Vec::new()));
let log_clone = log.clone();
let g = crate::go!{
log_clone.lock().unwrap().push(42);
};
let err = g.Wait();
assert!(err == crate::errors::nil);
assert_eq!(*log.lock().unwrap(), vec![42]);
}
#[test]
fn go_with_channel() {
let ch = crate::chan!(i64, 4);
let producer = ch.clone();
let g = crate::go!{
for i in 1i64..=3 {
producer.Send(i);
}
};
let _ = g.Wait();
let mut got: Vec<i64> = Vec::new();
for _ in 0..3 {
let (v, _) = ch.Recv();
got.push(v);
}
got.sort();
assert_eq!(got, vec![1, 2, 3]);
}
#[test]
fn panicking_goroutine_returns_error() {
let g = crate::go!{
panic!("boom");
};
let err = g.Wait();
assert!(err != crate::errors::nil);
}
}