简体   繁体   English

Rust 需要使用 Rayon 访问同一组数据的多线程密集型方法

[英]Rust multithread intensive methods which need to access same set of data with Rayon

I use Rayons par_iter() to iterate over different variations of the expensive method I need to run.我使用 Rayons par_iter()迭代我需要运行的昂贵方法的不同变体。 These runs need to access the same set of checked usizes because they all need to add to it and check it from time to time.这些运行需要访问同一组已检查的使用,因为它们都需要添加到它并不时检查它。 I also need them all to shutdown when first thread finishes, this is why I have a kill_switch which will force the iterations to exit when its set to true.我还需要它们在第一个线程完成时全部关闭,这就是为什么我有一个 kill_switch,它会在设置为 true 时强制迭代退出。

let mut checked: HashSet<usize> = HashSet::new();
let mut kill_switch: bool = false;

permutations.par_iter().for_each(|order| {
    let board = Board::new(board_map.clone(), order.clone());
    let mut bubbles: Vec<(i8, i8)> = Vec::new();
    if let Some(bubbles) = board.solve(&mut bubbles, &mut checked, &kill_switch) {
        kill_switch = true;
        bubbles.into_iter().for_each(|bubble| {
            dbg!(bubble);
        });
    }
})

This is the code I currently have but I get errors for how I'm using checked and kill_switch.这是我目前拥有的代码,但我在使用 checked 和 kill_switch 时遇到错误。 How do I make this work?我如何使这项工作?

Errors:错误:

  • cannot borrow checked as mutable, as it is a captured variable in a Fn closure cannot borrow as mutable [E0596]不能借用checked为可变的,因为它是Fn闭包中的捕获变量不能借用为可变的 [E0596]
  • cannot assign to kill_switch , as it is a captured variable in a Fn closure cannot assign [E0594]无法分配给kill_switch ,因为它是Fn闭包中捕获的变量无法分配 [E0594]

To fix the errors, you will need to use RefCells to wrap the checked and kill_switch variables and use the borrow_mut method to get a mutable reference to them in the closure.要修复这些错误,您需要使用 RefCells 包装 checked 和 kill_switch 变量,并使用 borrow_mut 方法在闭包中获取对它们的可变引用。

Here is an example of how you can modify your code:以下是如何修改代码的示例:

use std::cell::RefCell;
use std::collections::HashSet;

let checked: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
let kill_switch: RefCell<bool> = RefCell::new(false);

permutations.par_iter().for_each(|order| {
    let board = Board::new(board_map.clone(), order.clone());
    let mut bubbles: Vec<(i8, i8)> = Vec::new();
    if let Some(bubbles) = board.solve(&mut bubbles, &mut checked.borrow_mut(), &mut kill_switch.borrow_mut()) {
        *kill_switch.borrow_mut() = true;
        bubbles.into_iter().for_each(|bubble| {
            dbg!(bubble);
        });
    }
})

Note that you will also need to add RefCell as a dependency in your project.请注意,您还需要将 RefCell 添加为项目中的依赖项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM