如何在Rust中将参数传递给线程?

huangapple go评论108阅读模式
英文:

How to pass arguments to a thread in rust?

问题

  1. 我有一个我无法更改的闭包,我需要在一个新线程中运行它,并且我需要传递一个变量给它。我想代码看起来应该像这样:
  2. ```rust
  3. use std::thread;
  4. fn main() {
  5. // 我不能影响这个闭包,但它看起来是这样的
  6. let handle = move |data: i32| {
  7. println!("Got {}", data);
  8. };
  9. let foo = 123;
  10. // 这不起作用
  11. thread::spawn(move || handle(foo)).join();
  12. }
英文:

I have a closure which I cannot change, which I need to run in a new thread and to which I need to pass a variable. This is how I imagine the code to look like:

  1. use std::thread;
  2. fn main() {
  3. // I can not influence this closure, but this is what it looks like
  4. let handle = move |data: i32| {
  5. println!("Got {data}")
  6. };
  7. let foo = 123;
  8. // This doesn't work
  9. thread::spawn(handle).arg(foo).join()
  10. }

Equivalent code in Python is does work so I am wondering whether this is possible in rust and if so then how.

Thank you in advance.

答案1

得分: 5

  1. 文档中[thread::spawn()][1]的说明指出,它期望的输入是一个没有参数的闭包。因此,你不能直接使用你的`handle`闭包。但是,你可以创建一个没有参数的新闭包,调用你的`handle`闭包,像这样:
  2. ```rust
  3. use std::thread;
  4. fn main() {
  5. let handle = move |data: i32| {
  6. println!("收到数据 {data}")
  7. };
  8. let foo = 123;
  9. thread::spawn(move || {handle(foo)}).join();
  10. }
  1. <details>
  2. <summary>英文:</summary>
  3. The documentation for [thread::spawn()][1] indicates it expects as input a closure with no arguments. Therefore, you can&#39;t directly use your `handle` closure. However, you can create a new closure with no arguments that calls your `handle` closure like so:
  4. ```rust
  5. use std::thread;
  6. fn main() {
  7. let handle = move |data: i32| {
  8. println!(&quot;Got {data}&quot;)
  9. };
  10. let foo = 123;
  11. thread::spawn(move || {handle(foo)}).join();
  12. }

huangapple
  • 本文由 发表于 2023年4月7日 02:14:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定