i am junior dev and very new to rust but i did manage to write a small program using tokio.
it runs forever and executes some code at intervals in parallel.
it looks something like this:
but this does not run in parallel =(
only way i can get it to run in parallel (so far) is like this:
let runtime1 = tokio::runtime::Runtime::new().unwrap();
let runtime2 = tokio::runtime::Runtime::new().unwrap();
runtime1.spawn(async move { work1().await });
runtime2.spawn(async move { work2().await });
loop {}
but this is bananas, what am i missing and doing wrong?
edit for clarity: I want the intervals in work1 and work2 to execute in parallel, not concurrently, which is what I observe when using future::join_all(). one tokio::runtime per work() method achieves parallelism but does not look/feel right. how to do it properly?
Where is interval_at coming from? Are you using tokio::time::Instant or std::time::Instant? And do you mean you want it to run in parallel or concurrently?
The two (tokio 0.2. not run old) are giving the same result.
The lazy way to do so is add a small delay between spawning. The runtime isn't realtime so it's possible to glitch and temporarily not have the in-step output.
FYI, I tried your original code and it does run in parallel. (Though maybe your code was a little more elaborate) I simplified it to prove it. sleep will block a whole thread, which is not what you would typically want to do in async code, but if you run that, both values print at the same time indicating that they are running on two separate threads. If it was just concurrent on a single thread, one would print 2 seconds after the other.
Nice! but i am fairly certain that my code was only parallel after i configured threads on the main macro, maybe because i have my dev environment in docker or because i use interval_at, not sure.
anyway awaiting a join_all on tasks that run async intervals just exits the program =|
Did you have either the rt-threaded or full feature enabled when you first tried it? If not, according to the documentation tokio only runs code single threaded. Maybe that’s what you were seeing?
For your second comment, if you show some sample code that you expect to work but isn’t it’s easier to debug. Particularly it’s helpful to use the rust playground Link where you can actually run the code and share a link to it.