egui-tokio-example icon indicating copy to clipboard operation
egui-tokio-example copied to clipboard

Possibly redundent thread spawning in multi-threaded Tokio scheduler

Open zhongdongy opened this issue 2 years ago • 5 comments

Hi, thanks for this great example on how to use Tokio together with egui. It helps a lot. But I also have something in mind:

This line of code spawns a new std thread and execute some blocking async code inside. Your comments above that indicates the purpose is to execute the runtime in its own thread. But I think this is unnecessary because tokio::runtime::Runtime::new() itself creates a multi-threaded scheduler.

However, if we switch to tokio::runtime::Builder::new_current_thread().enable_all().build() while creating the runtime, a single-threaded executor will be created, thus we need to spawn another std thread for runtime execution.

Please point out my mistakes if any. Thank you!

zhongdongy avatar Mar 29 '23 03:03 zhongdongy

Ah yes, I meant to address this some time ago, but I lost sight of it. :( Thanks for the reminder.

I think we should try to keep the multithreaded runtime, and it should be possible to store the Runtime in MyApp. I don't know of a way to get tokio::spawn() to work without keeping an EnterGuard alive, which is why the code looks really awkward.

parasyte avatar Mar 29 '23 05:03 parasyte

It seems like a simple #[tokio::main] on main works and the GUI is running properly...

Is the egui doing some bad blocking stuff inside the tokio macro's expanded block_on call and that's why it's no good?

junderw avatar Aug 21 '23 04:08 junderw

@junderw It depends on the specific platform implementation, but the winit event loop is mostly blocking. And you can't use spawn_blocking to call eframe::run_native() because some platforms have hard requirements that the GUI can only run on the main thread.

parasyte avatar Aug 21 '23 21:08 parasyte