英文:
How to pass arguments to a thread in rust?
问题
我有一个我无法更改的闭包,我需要在一个新线程中运行它,并且我需要传递一个变量给它。我想代码看起来应该像这样:
```rust
use std::thread;
fn main() {
// 我不能影响这个闭包,但它看起来是这样的
let handle = move |data: i32| {
println!("Got {}", data);
};
let foo = 123;
// 这不起作用
thread::spawn(move || handle(foo)).join();
}
英文:
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:
use std::thread;
fn main() {
// I can not influence this closure, but this is what it looks like
let handle = move |data: i32| {
println!("Got {data}")
};
let foo = 123;
// This doesn't work
thread::spawn(handle).arg(foo).join()
}
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
文档中[thread::spawn()][1]的说明指出,它期望的输入是一个没有参数的闭包。因此,你不能直接使用你的`handle`闭包。但是,你可以创建一个没有参数的新闭包,调用你的`handle`闭包,像这样:
```rust
use std::thread;
fn main() {
let handle = move |data: i32| {
println!("收到数据 {data}")
};
let foo = 123;
thread::spawn(move || {handle(foo)}).join();
}
<details>
<summary>英文:</summary>
The documentation for [thread::spawn()][1] indicates it expects as input a closure with no arguments. Therefore, you can't directly use your `handle` closure. However, you can create a new closure with no arguments that calls your `handle` closure like so:
```rust
use std::thread;
fn main() {
let handle = move |data: i32| {
println!("Got {data}")
};
let foo = 123;
thread::spawn(move || {handle(foo)}).join();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论