use ckb_logger::debug;
use ckb_spawn::Spawn;
use ckb_stop_handler::{SignalSender, StopHandler};
use core::future::Future;
use std::thread;
use tokio::runtime::Builder;
use tokio::runtime::Handle as TokioHandle;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
#[derive(Debug, Clone)]
pub struct Handle {
pub(crate) inner: TokioHandle,
}
impl Handle {
pub fn enter<F, R>(&self, f: F) -> R
where
F: FnOnce() -> R,
{
self.inner.enter(f)
}
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.inner.spawn(future)
}
pub fn block_on<F: Future>(&self, future: F) -> F::Output {
self.inner.block_on(future)
}
}
pub fn new_global_runtime() -> (Handle, StopHandler<()>) {
let mut runtime = Builder::new()
.enable_all()
.threaded_scheduler()
.thread_name("ckb-global-runtime")
.build()
.expect("ckb runtime initialized");
let handle = runtime.handle().clone();
let (tx, rx) = oneshot::channel();
let thread = thread::Builder::new()
.name("ckb-global-runtime-tb".to_string())
.spawn(move || {
let ret = runtime.block_on(rx);
debug!("global runtime finish {:?}", ret);
})
.expect("tokio runtime started");
(
Handle { inner: handle },
StopHandler::new(SignalSender::Tokio(tx), Some(thread)),
)
}
impl Spawn for Handle {
fn spawn_task<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
{
self.spawn(future);
}
}