gpt4 book ai didi

thread-safety - 无法在线程之间发送 &str,因为它的生命周期不够长

转载 作者:行者123 更新时间:2023-11-29 08:06:23 25 4
gpt4 key购买 nike

给定以下简化程序:

#[macro_use] extern crate log;
extern crate ansi_term;
extern crate fern;
extern crate time;
extern crate threadpool;
extern crate id3;

mod logging;

use std::process::{exit, };
use ansi_term::Colour::{Yellow, Green};
use threadpool::ThreadPool;
use std::sync::mpsc::channel;
use std::path::{Path};
use id3::Tag;

fn main() {
logging::setup_logging();

let n_jobs = 2;

let files = vec!(
"/tmp/The Dynamics - Version Excursions/01-13- Move on Up.mp3",
"/tmp/The Dynamics - Version Excursions/01-09- Whole Lotta Love.mp3",
"/tmp/The Dynamics - Version Excursions/01-10- Feel Like Making Love.mp3"
);
let pool = ThreadPool::new(n_jobs);
let (tx, rx) = channel();
let mut counter = 0;

for file_ in files {
let file_ = Path::new(file_);
counter = counter + 1;
let tx = tx.clone();

pool.execute(move || {
debug!("sending {} from thread", Yellow.paint(counter.to_string()));

let tag = Tag::read_from_path(file_).unwrap();
let a_name = tag.artist().unwrap();

debug!("recursed file from: {} {}",
Green.paint(a_name), file_.display());

tx.send(".").unwrap();
// TODO amb: not working..
// tx.send(a_name).unwrap();
});
}

for value in rx.iter().take(counter) {
debug!("receiving {} from thread", Green.paint(value));
}
exit(0);
}

一切都按预期工作,除非注释行 (tx.send(a_name).unwrap();) 被放回原处。在那种情况下,我会收到以下错误:

error: `tag` does not live long enough
let a_name = tag.artist().unwrap();
^~~
note: reference must be valid for the static lifetime...
note: ...but borrowed value is only valid for the block suffix following statement 1 at 39:58
let tag = Tag::read_from_path(file_).unwrap();
let a_name = tag.artist().unwrap();

debug!("recursed file from: {} {}",
Green.paint(a_name), file_.display());

...

通常我理解编译器告诉我的内容,但我没有发现问题,因为变量 tag 是在闭包 block 内定义的。我能猜到的唯一问题是,变量 tx 是外部的 cloned,因此可能会与 tag 的生命周期发生冲突。

我的目标是将所有当前逻辑放在线程内部的 thread-closure 中,因为这是我想分散到多个线程的“处理”。我怎样才能做到这一点,但仍然向现有的时间较长的 tx 发送一些值?

我正在使用以下 Rust 版本:

$ rustc --version
rustc 1.9.0 (e4e8b6668 2016-05-18)
$ cargo --version
cargo 0.10.0-nightly (10ddd7d 2016-04-08)

最佳答案

a_name&strtag 借来的。因此,它的生命周期受限于 tag。将非 'static 引用沿 channel 发送到另一个线程是不安全的。它指的是线程堆栈上的某些东西,一旦接收者尝试访问它,它甚至可能不再存在。在您的情况下,您应该将 a_name 提升为 String 类型的自有值,该值将被移动到接收线程。

tx.send(a_name.to_owned()).unwrap();

关于thread-safety - 无法在线程之间发送 &str,因为它的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com