Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub struct TokioHandler {
- rt: Runtime // tokio runtime
- }
- static mut TOKIO_HANDLER = Lazy::new(|| Arc::new(RWLock::new(TokioHandler::new()) // из крейта once_cell
- impl TokioHandler {
- fn new() -> Self {
- Self {
- rt: tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap()
- }
- }
- pub fn launch_main_task<F: Future + Send + 'static>(&self, async_main_fn: F) -> F::Output {
- self.rt.block_on(async_main_fn)
- }
- pub fn launch_task<F: Future + Send + 'static>(&self, task: F) -> JoinHandle<F::Output> {
- self.rt.spawn(task)
- }
- }
- // Пример
- fn start_program() {
- let handler_clone = TOKIO_HANDLER.clone(); // клонируем ссылку, чтобы отправить в поток
- unsafe {
- TOKIO_HANDLER.read().unwrap().launch_main_task(async move {
- let handle = handler_clone.read().unwrap().launch_task(async { get_data(); }); // выполняется в другом потоке
- let data: Data = handle.await; // не блокирует потоки, только корутину
- // ...
- })
- }
- }
- fn get_data() -> Data {
- // ...
- }
Add Comment
Please, Sign In to add comment