Can tokio::runtime be used in wasm?
Asked Answered
K

1

5

everybody.

let rt = tokio::runtime::Runtime::new().unwrap();

This code doesn't work when I try to build wasm.

let rt = tokio::runtime::Runtime::new().unwrap();
   |                              ^^^^^^^ could not find `Runtime` in `runtimе
let rt = tokio::runtime::Runtime::new().unwrap();
    |                     ^^^^^^^ private module

Is it possible to use tokio::runtime in wasm or do I need to look for other ways ? Can I use multithreading ?

I tried to start an asynchronous function with rt.block_on, since the current function is not supposed to be asynchronous, it runs in a separate thread.

Kondon answered 1/11, 2023 at 10:45 Comment(0)
P
6

Tokio does have some support WASM, see WASM support in the docs. You need to enable the rt feature (the full feature doesn't work and causes a compilation failure). However, it does not support multi-threaded runtime (as WASM does not support threads), and therefore does not support Runtime::new(). You need to use tokio::runtime::Builder::new_current_thread() and enable the features you want with the methods (which is currently only time and only on WASI).

However, you should reconsider if you really need tokio. If you are in the browser, use the browser APIs and wasm-bindgen-futures to interact with JavaScript promises via async/await. If you are on WASI, still tokio provides only minimal support and you may want to look for something else.

Phenocryst answered 1/11, 2023 at 10:58 Comment(1)
If one has a application that wants to deploy both natively as well as on wasm, then interacting directly with promises etc. without abstractions will mean that practically you will have to develop and synchronize 2 applications. Thats why sometimes something such as tokio might make sense. Abstracting just over the spawning of a future is possible with bindgen-futures, but it doesnt posses eg. synchronization primitives. Though there are probably still smaller alternatives to tokio, such as embassy-rs.Dekow

© 2022 - 2025 — McMap. All rights reserved.