extern crate coroutine;
use std::thread::{self, Builder};
use std::sync::{Arc, Mutex};
use std::collections::VecDeque;
use coroutine::asymmetric::Coroutine;
fn main() {
let queue = Arc::new(Mutex::new(VecDeque::new()));
let mut threads = Vec::new();
for tid in 0..4 {
let queue = queue.clone();
let t = Builder::new().name(format!("Thread {}", tid)).spawn(move|| {
loop {
let coro: Coroutine<i32> = {
let mut queue = queue.lock().unwrap();
match queue.pop_front() {
Some(coro) => coro,
None => continue
}
};
let result = coro.resume().unwrap();
println!("{:?} {}", thread::current().name().unwrap_or("<unnamed>"), result.unwrap());
{
let mut queue = queue.lock().unwrap();
queue.push_back(coro);
}
}
}).unwrap();
threads.push(t);
}
{
let mut queue = queue.lock().unwrap();
queue.push_back(Coroutine::spawn(|me| {
for num in 0.. {
me.yield_with(num);
}
}));
}
for th in threads {
th.join().unwrap();
}
}