我正在尝试使用Rust线程。在我的示例中(人为设计,但基于实际问题),我想接受只读的HashMap
作为函数的参数,然后将其提供给多个线程,每个线程从其分区读取操作。
use std::{
collections::HashMap,
sync::{mpsc::channel, Arc},
thread,
};
const THREADS: u32 = 10;
// Concurrently add the lengths of values.
pub fn concurrent_lens(inputs: &HashMap<u32, String>) -> usize {
let inputs_arc = Arc::new(inputs);
let (tx, rx) = channel();
// Count length of all strings in parallel.
// Each thread takes a partition of the data.
for thread_i in 0..THREADS {
let tx = tx.clone();
let inputs_clone = inputs_arc.clone();
thread::spawn(move || {
for (i, content) in inputs_clone.iter() {
// Only look at my partition's keys.
if (i % THREADS) == thread_i {
// Something expensive with the string.
let expensive_operation_result = content.len();
tx.send(expensive_operation_result).unwrap();
}
}
});
}
// Join and sum results.
let mut result = 0;
for len in rx.iter() {
result += len;
}
result
}
但是,编译器会说:
error[E0621]: explicit lifetime required in the type of `inputs`
--> src/main.rs:21:9
|
10 | pub fn concurrent_lens(inputs: &HashMap<u32, String>) -> usize {
| ------ consider changing the type of `inputs` to `&'static std::collections::HashMap<u32, std::string::String>`
...
21 | thread::spawn(move || {
| ^^^^^^^^^^^^^ lifetime `'static` required
据我了解,我的选择是
inputs
设为静态。这是不可能的,因为它不是静态数据。input
的所有权(不获取引用)。所以我的功能是pub fn concurrent_lens(inputs: HashMap<u32, String>) -> usize
。这使编译器对其生命周期感到满意,但数据位于函数外部,并且生命周期更长。pub fn concurrent_lens(inputs: Arc<HashMap<u32, String>>) -> usize
。效果很好,但似乎是一个真正的泄漏抽象,因为调用代码不必知道它正在调用使用并发的函数。这些似乎都不对。我想念什么吗?