Should threads be short-lived?

Hi, I'm new to rust and I'm working on an application with a Slint GUI. The Slint docs recommend offloading most logic to a worker thread so the main thread can handle animations.

My question is this: should I create a single thread that lives for the duration of the application, and pass messages to it to invoke whatever callback I need executed? Or should I create a new thread each time a callback is invoked, and close them as soon as the callback is done executing?

For context, I'm coming from an Elixir background, where processes are cheap and ephemeral, so we spawn tons of them and they get closed as soon as they're out of work to do; but I can't tell from the Rust book or the Slint docs if threads should be treated the same way in Rust.

1 Like

Rust threads are OS threads. They are a lot more expensive to spawn than Elixir processes, goroutines or tokio tasks (aka green threads). I wouldn't spawn short-lived OS threads and rather use a long-lived worker thread to which I would pass the work that needs to be done concurrently in the background.

7 Likes

That's exactly what I wanted to know, thanks very much!

2 Likes

Rust async tasks are like this, so if you have a lot of work to do of this format, or if you just like the programming style, you might like to add an async runtime, which will manage a thread pool (or just a thread) to run these tasks.

5 Likes

Alternatively, rayon has a spawn that will run the function on its threadpool. This might be better if the function is primarily blocking (eg cpu-bound), though it should be basically equivalent to functions like tokio's spawn_blocking

2 Likes

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.