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

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

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&#39;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!(&quot;Got {data}&quot;)
    };

    let foo = 123;

    thread::spawn(move || {handle(foo)}).join();
}

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:

确定