multithreading - 在线程之间传递 hashmap 的 channel |陷入循环 | rust

标签 multithreading rust hashmap channel

我正在为网站 Exercism in rust 解决一个问题,我基本上尝试同时计算某些文本中不同字母出现的次数。我通过在线程之间传递 HashMap 来做到这一点,并且不知何故处于某种无限循环中。我认为问题出在我对接收器的处理上,但我真的不知道。请帮忙。

use std::collections::HashMap;
use std::thread;
use std::sync::mpsc;
use std::str;

pub fn frequency(input: &[&str], worker_count: usize) -> HashMap<char, usize> {
   
   // Empty case 
   if input.is_empty() {
       return HashMap::new();
   }

   // Flatten input, set workload for each thread, create hashmap to catch results
   let mut flat_input = input.join("");
   let workload = input.len() / worker_count;
   let mut final_map: HashMap<char, usize> = HashMap::new();

   
   let (tx, rx) = mpsc::channel();
   for _i in 0..worker_count {
       let task = flat_input.split_off(flat_input.len() - workload);
       let tx_clone = mpsc::Sender::clone(&tx);

       
       // Separate threads ---------------------------------------------
       thread::spawn(move || {
          let mut partial_map: HashMap<char, usize> = HashMap::new();
          for letter in task.chars() {
              match partial_map.remove(&letter) {
                  Some(count) => {
                      partial_map.insert(letter, count + 1);
                  },
                  None => {
                      partial_map.insert(letter, 1);
                  }
              }
          }
          tx_clone.send(partial_map).expect("Didn't work fool");
       });
       // --------------------------------------------------  
       
   }
   
   // iterate through the returned hashmaps to update the final map
   for received in rx {
       for (key, value) in received {
           match final_map.remove(&key) {
               Some(count) => {
                   final_map.insert(key, count + value);
               },
               None => {
                   final_map.insert(key, value);
               }  
           }
       }
   }
   
   return final_map;
}

最佳答案

迭代接收者 rx 将在发送者存在时阻止新消息。克隆到线程中的那些将在完成后退出范围,但原始发件人 tx 仍在范围内。

您可以通过手动删除 tx 使其超出范围:

for _i in 0..worker_count {
    ...
}

std::mem::drop(tx); // <--------

for received in rx {
    ...
}

关于multithreading - 在线程之间传递 hashmap 的 channel |陷入循环 | rust ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65649189/

相关文章:

java - 在 servlet 中启动一个新线程

Java 最佳实践 : Put/Get SubClass objects into HashMap that expects SuperClass objects

java - EmployeeStore 的 SearchByEmail 方法(HashMap)

java - 我如何为执行程序选择线程数

java - 在 Java 中使用线程进行并行编程

c# - 在线程中使用 C# 将字符串添加到 WPF 中的列表框

rust - Rust 中的浅复制和移动

macros - 有没有办法让 Rust 宏像在 C 中一样充当文本替换?

rust - 使用 rustc_serialize 并获取不带引号的字符串

java - 具有不同哈希值的键是否也会映射到 HashMap 中的相同索引?