跨多个线程使用 Chunks 迭代器时,值的存活时间不够长 [英] Value does not live long enough when using the Chunks iterator across multiple threads

查看:50
本文介绍了跨多个线程使用 Chunks 迭代器时,值的存活时间不够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况的一个简化示例:

This is a simplified example of my situation:

use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

struct User {
    reference: String,
    email: String,
}

fn main() {
    let rows = vec![
        vec!["abcd", "test@test.com"],
        vec!["efgh", "test1@test.com"],
        vec!["wfee", "test2@test.com"],
        vec!["rrgr", "test3@test.com"],
    ];

    let chunk_len = (rows.len() / 2) as usize;
    let mut chunks = Vec::new();
    for chunk in rows.chunks(chunk_len) {
        chunks.push(chunk);
    }

    let (tx, rx): (Sender<Vec<User>>, Receiver<Vec<User>>) = mpsc::channel();

    for chunk in chunks {
        let thread_tx = tx.clone();
        thread::spawn(move || {
            let result = chunk
                .iter()
                .map(|row| {
                    User {
                        reference: row[0].to_string(),
                        email: row[1].to_string(),
                    }
                })
                .collect::<Vec<User>>();
            thread_tx.send(result).unwrap();
        });
    }

    let mut users = Vec::new();
    for _ in 0..chunk_len {
        users.push(rx.recv());
    }
}

它抛出一个错误

error[E0597]: `rows` does not live long enough
  --> src/main.rs:20:18
   |
20 |     for chunk in rows.chunks(chunk_len) {
   |                  ^^^^ does not live long enough
...
47 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

我尝试更改为 chunks.push(chunk.clone()); 但错误仍然不会消失.我在这里错过了什么?

I tried to change to chunks.push(chunk.clone()); but the error still wouldn't go away. What am I missing here?

推荐答案

该错误看起来确实具有误导性,但它是正确的.您的问题实际上是 chunks()slices 的迭代器提供给原始向量:

The error does look misleading, however, it is correct. Your problem in fact is that chunks() gives an iterator of slices into the original vector:

impl<'a, T> Iterator for Chunks<'a, T> {
    type Item = &'a [T];
}

您正在尝试在 spawn() ed 线程中使用此切片,该线程要求闭包具有 'static 生命周期:

You're trying to use this slice in a spawn()ed thread which requires the closure to have the 'static lifetime:

pub fn spawn<F, T>(f: F) -> JoinHandle<T> 
where
    F: FnOnce() -> T,
    F: Send + 'static,
    T: Send + 'static, 

您的迭代器确实具有 'static 生命周期,因为它包含对运行时分配向量的引用.

Your iterator does have the 'static lifetime because it contains references to a runtime-allocated vector.

您说您尝试过 clone(),但这只是克隆切片,它不会为您提供新向量.为此,您需要使用 to_owned():

You said that you tried clone(), but that only clones the slice, it does not give you a new vector. For that you need to use to_owned():

for chunk in rows.chunks(chunk_len) {
    chunks.push(chunk.to_owned());
}

瞧,它编译.

这篇关于跨多个线程使用 Chunks 迭代器时,值的存活时间不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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