Can I start two tokio runtimes in two separate std::thread?

hi, I'm trying to introduce the deno_core (v8) into my command line, and evaluate some javascript codes.

I want to use tokio to manage some IO (also including the termnal keyboard/mouse events through crossterm EventStream) and background jobs. Let's name this runtime the A.

But V8 need to run in a completely single thread. And some javascript language features such as Promise and async keyword inside V8 usually need to be handled with async jobs, i.e. a tokio's task. So I want to create another tokio runtime (let's name it B) for handling these async tasks for V8.

Can I do it like this?

I cannot really comment much on whether it’s the best choice for your particular use-case (I haven’t done any combination of Rust+Javascript before), but in principle, using multiple tokio runtimes should be easy to do and should work just fine. The relevant API for setting up a runtime is of course in tokio::runtime.

The likes of Runtime::enter does use some implicit global variables, however those are only thread-local (and even support proper nesting for all I can tell, so you could in principle even .enter() a different runtime in a sub-scope, even in the same thread). So anyways, separate Rust threads can work completely independently as far as tokio runtimes go.

4 Likes

Depending on what you need, using a second runtime for this is either unnecessary or futile. Tokio spawned tasks are always potentially run on different threads (they must be Send). If you need to run multiple !Send tasks on a specific thread, create a LocalSet to run them.

4 Likes

thanks for your suggestions. Actually I am not 100% sure about V8, still working on it. I will have a try.

Thanks for your answer about the safety of using two runtimes in two separate thread. I will have some try on my special needs.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.