gpt4 book ai didi

multithreading - 我如何将非静态数据发送到 Rust 中的线程,此示例是否需要它?

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

我正在尝试使用 Rust 中的一些堆数据启动一个新线程,但我收到了一堆错误,这些错误源于数据需要具有 'static 生命周期。我已经按照我的方式倒退了我的程序,但遇到了问题。

use std::sync::Arc;
use std::thread;

struct ThreadData {
vector_of_strings: Vec<String>,
terms: Vec<&'static str>,
quotient: usize,
}

fn perform_search(slice: &[String], terms: &[&str]) {
/* ... */
}

fn threaded_search(td_arc: &Arc<ThreadData>) {
let no_of_lines = td_arc.vector_of_strings.len();
let new_tda1 = td_arc.clone();

let strings_as_slice1 = new_tda1.vector_of_strings.as_slice();

thread::spawn(move || {
perform_search(&strings_as_slice1[0..td_arc.quotient], &new_tda1.terms);
});
}

fn main() {
let td = ThreadData {
vector_of_strings: Vec::new(),
terms: Vec::new(),
quotient: 0,
};

let td_arc = Arc::new(td);
threaded_search(&td_arc);
}

错误:

error[E0621]: explicit lifetime required in the type of `td_arc`               
--> src/main.rs:20:5
|
14 | fn threaded_search(td_arc: &Arc<ThreadData>) {
| ---------------- help: add explicit lifetime `'static` to the type of `td_arc`: `&'static std::sync::Arc<ThreadData>`
...
20 | thread::spawn(move || {
| ^^^^^^^^^^^^^ lifetime `'static` required

最佳答案

关于 'static 的错误是因为在 thread::spawn 中创建的新线程可能比 threaded_search 的调用更有效,在此期间线程最初创建,这意味着不得允许线程使用 threaded_search 中的任何局部变量,其生命周期短于 'static

在您的代码中,新线程指的是 strings_as_slice1td_arc

通常对于 thread::spawnArc,您将希望将一个引用计数的所有权移动到线程中,并让线程通过该引用计数访问它需要的任何内容指针,而不是直接来自封闭的短期作用域。

fn threaded_search(td_arc: &Arc<ThreadData>) {
// Increment reference count that we can move into the new thread.
let td_arc = td_arc.clone();

thread::spawn(move || {
perform_search(&td_arc.vector_of_strings[0..td_arc.quotient], &td_arc.terms);
});
}

关于multithreading - 我如何将非静态数据发送到 Rust 中的线程,此示例是否需要它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52437174/

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