当前位置:   article > 正文

RUST——线程创建_rust spwan 是线程嘛

rust spwan 是线程嘛

用spawn创建线程

在rust中创建线程是通过标准库中的thread::spawn函数来创建线程,spawn函数的参数是一个闭包,创建线程的示例代码如下:

  1. use std::thread;
  2. use std::time::Duration;
  3. fn main() {
  4. thread::spawn(|| {
  5. for i in 1..10 {
  6. println!("hi number {} from the spawned thread!", i);
  7. thread::sleep(Duration::from_millis(1));
  8. }
  9. });
  10. for i in 1..5 {
  11. println!("hi number {} from the main thread!", i);
  12. thread::sleep(Duration::from_millis(1));
  13. }
  14. }

用join方法等等待线程结束

在上面的例子中,我们只是创建了线程,但是主线程并没有等待子线程结束执行。这样一来,当主线程结束的时候,不论子线程是否结束,都会结束执行。为了让主线程等待子线程结束执行,我们使用join方法来实现这一功能,示例代码如下:

  1. use std::thread;
  2. use std::time::Duration;
  3. fn main() {
  4. let handle = thread::spawn(|| {
  5. for i in 1..10 {
  6. println!("hi number {} from the spawned thread!", i);
  7. thread::sleep(Duration::from_millis(1));
  8. }
  9. });
  10. for i in 1..5 {
  11. println!("hi number {} from the main thread!", i);
  12. thread::sleep(Duration::from_millis(1));
  13. }
  14. handle.join().unwrap();
  15. }

关于move语义的使用

如果我们需要在新创建的线程中使用主线程中的数据,我们需要使用rust中的move语义,来转移数据的所有权,以实现线程安全。

  1. 不使用move语义的示例代码
  1. use std::thread;
  2. fn main() {
  3. let v = vec![1, 2, 3];
  4. let handle = thread::spawn(|| {
  5. println!("Here's a vector: {:?}", v);
  6. });
  7. handle.join().unwrap();
  8. }

在上面的示例代码中,我们在新创建的子线程中使用了在主线程中定义的向量v,如果我们编译上面的代码,我们会得到以下结果:

  1. Compiling thread_move_demo v0.1.0 (E:\CLionProjects\thread_move_demo)
  2. error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
  3. --> src\main.rs:6:32
  4. |
  5. 6 | let handle = thread::spawn(|| {
  6. | ^^ may outlive borrowed value `v`
  7. 7 | println!("Here is a vector: {:?}", v);
  8. | - `v` is borrowed here
  9. |
  10. note: function requires argument type to outlive `'static`
  11. --> src\main.rs:6:18
  12. |
  13. 6 | let handle = thread::spawn(|| {
  14. | __________________^
  15. 7 | | println!("Here is a vector: {:?}", v);
  16. 8 | | });
  17. | |______^
  18. help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
  19. |
  20. 6 | let handle = thread::spawn(move || {
  21. | ++++
  22. For more information about this error, try `rustc --explain E0373`.
  23. error: could not compile `thread_move_demo` due to previous error

从上面编译的结果可以看出来,rust提示我们需要使用move把向量v的所有权转移到新创建的子线程上去,故而修改后的代码如下所示:

  1. use std::thread;
  2. fn main() {
  3. let v = vec![1, 2, 3];
  4. let handle = thread::spawn(move || {
  5. println!("Here is a vector: {:?}", v);
  6. });
  7. handle.join().unwrap();
  8. }

代码执行的结果如下所示:

Here is a vector: [1, 2, 3]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/847172
推荐阅读
相关标签
  

闽ICP备14008679号