有没有办法在生成的线程中调用闭包?

时间:2015-06-02 16:43:55

标签: multithreading rust

我有一个功能:

fn awesome_function<F>(v: Vec<u64>, f: F)
    where F: Fn(u64) -> String
{ /* ... */ }

有没有办法调用在生成的线程中传递的函数?类似的东西:

...
thread::spawn(move || f(1));
...

我尝试了几种不同的方法,但收到错误error: the trait core::marker::Send is not implemented for the type F [E0277]

1 个答案:

答案 0 :(得分:5)

绝对。您要做的主要事情是将F限制为Send

use std::thread;

fn awesome_function<F>(v: Vec<u64>, f: F) -> String
    where F: Fn(u64) + Send + 'static
{
    thread::spawn(move || f(1));
    unimplemented!()
}

fn main() {}

您还需要将其限制为'staticthread::spawn也是如此。

相关问题