Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, how can I create task that runs in its own OS thread?

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.

like image 996
McPherrinM Avatar asked Nov 12 '13 07:11

McPherrinM


People also ask

Is Rust good for multithreading?

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.

What is a Tokio task?

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.

How do you make threads in Rust?

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.

How many threads can Rust run?

Therefore, a Rust program has no limit imposed by Rust itself, but rather, this limit would result from whatever your OS lets you do.


1 Answers

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

}
like image 111
Zargony Avatar answered Nov 11 '22 12:11

Zargony