6

Is there a way to specify a single-threaded runtime using the attribute #[tokio::main] in tokio 0.2? The doc does not seem to have examples for that.

EDIT: I wanted to find a way to set up tokio runtime so that rustc is aware of tokio:spawn() will not be a new thread.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
user1783732
  • 1,599
  • 5
  • 22
  • 44

1 Answers1

9

Newer answer, applicable for Tokio 0.3.0 and above

The documentation for tokio::main shows what options it has. It is quite common to want to start the current-thread runtime, so there is a special option for it:

#[tokio::main(flavor = "current_thread")]

Old answer, applicable for Tokio < 0.3.0

The documentation for tokio::main shows what options it has:

core_threads=n - Sets core threads to n (requires rt-threaded feature). max_threads=n - Sets max threads to n (requires rt-core or rt-threaded feature).

Thus:

#[tokio::main(core_threads = 1, max_threads = 1)]
async fn main() {
    println!("Hello world");
}

If this does not work for whatever your case is, you will have to directly create a runtime as shown in How do I synchronously return a value calculated in an asynchronous Future?.

Qqwy
  • 5,214
  • 5
  • 42
  • 83
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Thanks for your answer. I should have clarified that I wanted to find a way to have tokio executor runs on the single (current) thread, instead of thread pool of size 1. The reason is that I wanted `rustc` is aware of all tasks are in a single thread, so no need to check for thread safety issues. Later I tried the approach of using `basic_scheduler`, but it seems that `rustc` still thinks it's a new thread when I call `tokio::spawn()`. – user1783732 May 14 '20 at 16:40
  • 1
    @user1783732 why wouldn’t you have asked the question you wanted to solve? You are demonstrating the [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Your problem [isn’t unique to Tokio or async](https://stackoverflow.com/q/32750829/155423) and shows a fundamental misunderstanding of what the Rust compiler is capable of. – Shepmaster May 14 '20 at 16:45
  • 1
    @user1783732 You can use [LocalSet](https://docs.rs/tokio/latest/tokio/task/struct.LocalSet.html) and `spawn_local` to limit execution to a single thread. It allows having `!Send` variable over `.await` boundary, which sounds like what you're looking for. – quartzsaber Jan 16 '22 at 15:03