赞
踩
在rust中创建线程是通过标准库中的thread::spawn函数来创建线程,spawn函数的参数是一个闭包,创建线程的示例代码如下:
- use std::thread;
- use std::time::Duration;
-
- fn main() {
- thread::spawn(|| {
- for i in 1..10 {
- println!("hi number {} from the spawned thread!", i);
- thread::sleep(Duration::from_millis(1));
- }
- });
-
- for i in 1..5 {
- println!("hi number {} from the main thread!", i);
- thread::sleep(Duration::from_millis(1));
- }
- }
在上面的例子中,我们只是创建了线程,但是主线程并没有等待子线程结束执行。这样一来,当主线程结束的时候,不论子线程是否结束,都会结束执行。为了让主线程等待子线程结束执行,我们使用join方法来实现这一功能,示例代码如下:
- use std::thread;
- use std::time::Duration;
-
- fn main() {
- let handle = thread::spawn(|| {
- for i in 1..10 {
- println!("hi number {} from the spawned thread!", i);
- thread::sleep(Duration::from_millis(1));
- }
- });
-
- for i in 1..5 {
- println!("hi number {} from the main thread!", i);
- thread::sleep(Duration::from_millis(1));
- }
-
- handle.join().unwrap();
- }
如果我们需要在新创建的线程中使用主线程中的数据,我们需要使用rust中的move语义,来转移数据的所有权,以实现线程安全。
- use std::thread;
-
- fn main() {
- let v = vec![1, 2, 3];
-
- let handle = thread::spawn(|| {
- println!("Here's a vector: {:?}", v);
- });
-
- handle.join().unwrap();
- }
在上面的示例代码中,我们在新创建的子线程中使用了在主线程中定义的向量v,如果我们编译上面的代码,我们会得到以下结果:
- Compiling thread_move_demo v0.1.0 (E:\CLionProjects\thread_move_demo)
- error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
- --> src\main.rs:6:32
- |
- 6 | let handle = thread::spawn(|| {
- | ^^ may outlive borrowed value `v`
- 7 | println!("Here is a vector: {:?}", v);
- | - `v` is borrowed here
- |
- note: function requires argument type to outlive `'static`
- --> src\main.rs:6:18
- |
- 6 | let handle = thread::spawn(|| {
- | __________________^
- 7 | | println!("Here is a vector: {:?}", v);
- 8 | | });
- | |______^
- help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
- |
- 6 | let handle = thread::spawn(move || {
- | ++++
- For more information about this error, try `rustc --explain E0373`.
- error: could not compile `thread_move_demo` due to previous error
从上面编译的结果可以看出来,rust提示我们需要使用move把向量v的所有权转移到新创建的子线程上去,故而修改后的代码如下所示:
- use std::thread;
-
- fn main() {
- let v = vec![1, 2, 3];
-
- let handle = thread::spawn(move || {
- println!("Here is a vector: {:?}", v);
- });
-
- handle.join().unwrap();
- }
代码执行的结果如下所示:
Here is a vector: [1, 2, 3]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。