您可以为线程指定非静态生存期吗? [英] Can you specify a non-static lifetime for threads?

查看:48
本文介绍了您可以为线程指定非静态生存期吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题的一个玩具例子:

Here's a toy example of my problem:

use std::sync::{Arc, Mutex};

fn operate_in_chunks(vec: &mut Vec<f32>) {
    let chunk_size = 10;
    let mutex_vec: Arc<Mutex<&mut Vec<f32>>> = Arc::new(Mutex::new(vec));

    let handles = Vec::new();

    for chunk in 0..vec.len() / chunk_size {
        handles.push(std::thread::spawn(move || {
            operate(mutex_vec, chunk);
        }));
    }

    for i in 0..handles.len() {
        handles[i].join().unwrap();
    }
}

fn operate(mutex_vec: Arc<Mutex<&mut Vec<f32>>>, chunk: usize) {}

我想对传入的结构进行一些工作,将其拆分为多个线程,然后在返回之前将它们重新结合在一起.

I'd like to do some work on the passed-in struct, split among a number of threads, and then join them all back together before returning.

我得到的错误是:

error[E0621]: explicit lifetime required in the type of `vec`
  --> src/lib.rs:10:22
   |
3  | fn operate_in_chunks(vec: &mut Vec<f32>) {
   |                           ------------- help: add explicit lifetime `'static` to the type of `vec`: `&'static mut std::vec::Vec<f32>`
...
10 |         handles.push(std::thread::spawn(move || {
   |                      ^^^^^^^^^^^^^^^^^^ lifetime `'static` required

我了解它在抱怨什么:如果线程可能具有'static 生存期,并且它们引用 vec ,则 vec 必须具有静态"生存期.但是,我的用例在理论上应该可行:我想保证线程不要的生存期为'static ,因为所有线程都在函数返回,在这种情况下,我不需要在 vec`上使用' static'生存期.

I understand what it's complaining about: if the threads may have a 'static lifetime, and they reference vec, vec must have a 'static lifetime. However, my use-case should in theory be possible: I want to guarantee that the threads don't have a 'static lifetime, as they're all joined before the function returns, in which case I shouldn't need a 'static' lifetime onvec`.

Rust是否有一种表达方式-将线程的生存期与 vec 的生​​存期统一-还是所有线程始终保持'static 不变?

Does Rust have a way of articulating this - unifying the lifetime of the threads with the lifetime of vec - or are all threads always 'static no matter what?

推荐答案

Rust实际上用于允许范围内的线程,该线程允许所传递的任何数据的非静态生存期.但是,发现该API不健全,并在大约两年后被删除.幸运的是, crossbeam 是一个板条箱,可使用不同的API,可让您安全地使用此功能.来自crossbeam文档的示例在这里:

Rust actually used to allow scoped threads, which allow non-static lifetimes for any data passed. However, the API was found to be unsound and they were removed around two years ago. Fortunately, crossbeam, a crate, implements scoped threads with a different API allowing you to use this functionality safely. A sample from crossbeam's documentation is here:

let array = [1, 2, 3];

crossbeam::scope(|scope| {
    for i in &array {
        scope.spawn(move || {
            println!("element: {}", i);
        });
    }
});

这篇关于您可以为线程指定非静态生存期吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆