This question is no longer relevant: Rust green threading is gone. All tasks correspond to a thread.
Rust tasks run in a pool of threads managed by the runtime.
I am calling some code via the FFI that will block, and I'll be doing it in a tight loop.
How do I spawn a task on its own OS thread?
The two concerns are that the thread stays scheduled on its thread, and that the work stealing scheduler doesn't bring additional work onto this thread.
Rust attempts to mitigate the negative effects of using threads, but programming in a multithreaded context still takes careful thought and requires a code structure that is different from that in programs running in a single thread.
A task is a light weight, non-blocking unit of execution. A task is similar to an OS thread, but rather than being managed by the OS scheduler, they are managed by the Tokio runtime. Another name for this general pattern is green threads.
To create a new thread in Rust, we call the thread::spawn function and then pass it a closure, which in turn contains the code that we want to run in the new thread.
Therefore, a Rust program has no limit imposed by Rust itself, but rather, this limit would result from whatever your OS lets you do.
With std::task::spawn_sched, you can spawn tasks on a new, single-threaded scheduler that will run on its own OS thread.
use std::task::{spawn_sched, SingleThreaded};
do spawn_sched(SingleThreaded) {
// This runs in its own OS thread
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With