Files
tokio/src/reactor/global.rs
T

55 lines
1.3 KiB
Rust
Raw Normal View History

2017-12-05 09:47:29 -08:00
use std::io;
use std::thread;
2017-12-12 15:19:39 -06:00
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
2017-12-05 09:47:29 -08:00
use reactor::{Reactor, Handle};
pub struct HelperThread {
thread: Option<thread::JoinHandle<()>>,
reactor: Handle,
2017-12-12 15:19:39 -06:00
done: Arc<AtomicBool>,
2017-12-05 09:47:29 -08:00
}
impl HelperThread {
pub fn new() -> io::Result<HelperThread> {
let reactor = Reactor::new()?;
let reactor_handle = reactor.handle().clone();
2017-12-12 15:19:39 -06:00
let done = Arc::new(AtomicBool::new(false));
let done2 = done.clone();
let thread = thread::Builder::new().spawn(move || run(reactor, done))?;
2017-12-05 09:47:29 -08:00
Ok(HelperThread {
thread: Some(thread),
reactor: reactor_handle,
2017-12-12 15:19:39 -06:00
done: done2,
2017-12-05 09:47:29 -08:00
})
}
pub fn handle(&self) -> &Handle {
&self.reactor
}
pub fn forget(mut self) {
drop(self.thread.take());
}
}
impl Drop for HelperThread {
fn drop(&mut self) {
2017-12-12 15:19:39 -06:00
let thread = match self.thread.take() {
Some(thread) => thread,
None => return
};
self.done.store(true, Ordering::SeqCst);
self.reactor.wakeup();
thread.join().unwrap();
2017-12-05 09:47:29 -08:00
}
}
2017-12-12 15:19:39 -06:00
fn run(mut reactor: Reactor, done: Arc<AtomicBool>) {
while !done.load(Ordering::SeqCst) {
reactor.turn(None).unwrap();
2017-12-05 09:47:29 -08:00
}
}