#[main]
Expand description
Marks async function to be executed by selected runtime. This macro helps set up a Runtime
without requiring the user to use Runtime or
Builder directly.
Options:
If you want to set the number of worker threads used for asynchronous code, use the
core_threads
option.
core_threads=n
- Sets core threads ton
(requiresrt-threaded
feature).max_threads=n
- Sets max threads ton
(requiresrt-core
orrt-threaded
feature).basic_scheduler
- Use the basic schduler (requiresrt-core
).
Function arguments:
Arguments are allowed for any functions aside from main
which is special
Usage
Using default
#[tokio::main]
async fn main() {
println!("Hello world");
}
Equivalent code not using #[tokio::main]
fn main() {
tokio::runtime::Builder::new()
.threaded_scheduler()
.enable_all()
.build()
.unwrap()
.block_on(async {
println!("Hello world");
})
}
Using basic scheduler
The basic scheduler is single-threaded.
#[tokio::main(basic_scheduler)]
async fn main() {
println!("Hello world");
}
Equivalent code not using #[tokio::main]
fn main() {
tokio::runtime::Builder::new()
.basic_scheduler()
.enable_all()
.build()
.unwrap()
.block_on(async {
println!("Hello world");
})
}
Set number of core threads
#[tokio::main(core_threads = 2)]
async fn main() {
println!("Hello world");
}
Equivalent code not using #[tokio::main]
fn main() {
tokio::runtime::Builder::new()
.threaded_scheduler()
.core_threads(2)
.enable_all()
.build()
.unwrap()
.block_on(async {
println!("Hello world");
})
}
NOTE:
If you rename the tokio crate in your dependencies this macro
will not work. If you must rename the 0.2 version of tokio because
you’re also using the 0.1 version of tokio, you must make the
tokio 0.2 crate available as tokio
in the module where this
macro is expanded.