【笔记】Rust的异步

Introduction

Rust achieves multi-threading through asynchronous programming.

Executing Functions with Multiple Threads

1
2
3
4
5
6
7
8
9
10
11
12
fn function_name() {
...
}

fn main() {
let thread_variable_1 = spawn(function_name);
let thread_variable_2 = spawn(function_name);

// Wait for the child threads to finish executing before exiting the program
thread_variable_1.join().unwrap();
thread_variable_2.join().unwrap();
}

Implementing with External Packages

Importing Dependencies

/Cargo.toml
1
2
[dependencies]
async-std = { version = "1.12.0", features = ["attributes"] }

Multi-threading

1
2
3
4
5
6
7
8
9
10
11
12
13
async fn function_name() {
...
sleep(Duration::from_millis(500)).await;
}

#[async_std::main]
async fn main() {
let thread_variable = spawn(function_name());

// Wait for the child threads to finish executing before exiting the program
thread_variable.await;
function_name().await;
}

Done

References

哔哩哔哩——面向加薪学习