簡體   English   中英

Rust 需要使用 Rayon 訪問同一組數據的多線程密集型方法

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

我使用 Rayons par_iter()迭代我需要運行的昂貴方法的不同變體。 這些運行需要訪問同一組已檢查的使用,因為它們都需要添加到它並不時檢查它。 我還需要它們在第一個線程完成時全部關閉,這就是為什么我有一個 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);
        });
    }
})

這是我目前擁有的代碼,但我在使用 checked 和 kill_switch 時遇到錯誤。 我如何使這項工作?

錯誤:

  • 不能借用checked為可變的,因為它是Fn閉包中的捕獲變量不能借用為可變的 [E0596]
  • 無法分配給kill_switch ,因為它是Fn閉包中捕獲的變量無法分配 [E0594]

要修復這些錯誤,您需要使用 RefCells 包裝 checked 和 kill_switch 變量,並使用 borrow_mut 方法在閉包中獲取對它們的可變引用。

以下是如何修改代碼的示例:

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);
        });
    }
})

請注意,您還需要將 RefCell 添加為項目中的依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM