Attribute Macro main

Source
#[main]
Expand description

Configures main to be executed by the selected Tokio runtime

§Borrowing the runtime

To borrow the runtime directly, add as a function argument

#[async_local::main(flavor = "multi_thread", worker_threads = 10)]
fn main(runtime: &tokio::runtime::Runtime) {}

§Non-worker async function

Note that the async function marked with this macro does not run as a worker. The expectation is that other tasks are spawned by the function here. Awaiting on other futures from the function provided here will not perform as fast as those spawned as workers.

§Multi-threaded runtime

To use the multi-threaded runtime, the macro can be configured using

#[async_local::main(flavor = "multi_thread", worker_threads = 10)]

The worker_threads option configures the number of worker threads, and defaults to the number of cpus on the system. This is the default flavor.

Note: The multi-threaded runtime requires the rt-multi-thread feature flag.

§Current thread runtime

To use the single-threaded runtime known as the current_thread runtime, the macro can be configured using

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

§Usage

§Using the multi-thread runtime

#[async_local::main]
async fn main() {
  println!("Hello world");
}

§Using current thread runtime

The basic scheduler is single-threaded.

#[async_local::main(flavor = "current_thread")]
async fn main() {
  println!("Hello world");
}

§Set number of worker threads

#[async_local::main(worker_threads = 2)]
async fn main() {
  println!("Hello world");
}

§Configure the runtime to start with time paused

#[async_local::main(flavor = "current_thread", start_paused = true)]
async fn main() {
  println!("Hello world");
}

Note that start_paused requires the test-util feature to be enabled on tokio.