#2.19. par:平行處理 API
本頁內容
core::par 模組提供資料平行的 API。它的設計參考 Rust 的 Rayon,並在與 task::* 相同的工作竊取(work-stealing)排程器上執行。
par 模組在 prelude 中,所以 par::for_each、par::map 等不需匯入即可使用;模組前綴 par:: 仍然保留。若要讓平行的意圖一目了然,建議明確寫出 use core::par::*;。
#2.19.1. 核心 API
核心 API 由七個函式組成;try_scope(2.19.3)是第八個。
fn for_each<I: IntoIterator<Item = T>, T: Send>(iter: I, f: fn(T) + Send + Sync);
fn map<I: IntoIterator<Item = T>, T: Send, U: Send>(iter: I, f: fn(T) -> U + Send + Sync) -> List<U>;
fn fold<I: IntoIterator<Item = T>, T: Send>(iter: I, init: T, f: fn(T, T) -> T + Send + Sync) -> T;
fn reduce<I: IntoIterator<Item = T>, T: Send>(iter: I, f: fn(T, T) -> T + Send + Sync) -> T | none;
fn filter<I: IntoIterator<Item = T>, T: Send>(iter: I, pred: fn(T) -> bool + Send + Sync) -> List<T>;
fn join<T1: Send, T2: Send>(f1: fn() -> T1 + Send, f2: fn() -> T2 + Send) -> (T1, T2); // 2 in parallel
fn scope(f: fn(Scope)); // dynamic spawn
所有接受項目的函式都接受任何 IntoIterator。它們共用一組約束:項目是 T: Send,而 for_each / map / fold / reduce / filter 的 f 會同時被多個工作者呼叫,所以是 + Send + Sync。
map/filter結果List的順序與輸入相同。for_each在多個工作者上同時呼叫f,所以呼叫的順序未指定。for_each/map/filter/fold/reduce把每個項目交給一個工作者。兩個項目不得觸及同一個非Sync的集合型別(2.13.9)。每次呼叫會先尋找由兩個項目都能觸及的集合型別:它沿著項目的組成部分及其集合型別的元素追蹤到任意深度,與移交時的複製相同,但不進入只含純值(數字、bool、str)的集合型別。若找到一個,這些項目會在呼叫端執行緒上逐一執行,因此不會發生競爭,就地變更的結果也與使用工作者時相同,並且會發出一則指出呼叫位置的警告(每個位置一次)。切片只會讀取:項目可以透過一個串列的切片共用該串列(一個大串列的各個區塊),只要沒有任何項目持有串列本身;切片觸及的元素會逐一追蹤。可寫入的檢視(SliceMut,來自chunks_mut或split_at_mut)也可以共用串列:檢查會記下每個項目的檢視與切片涵蓋串列的哪一部分,當一個項目寫入的部分與另一個項目讀取或寫入的部分重疊,或另一個項目持有整個串列時,這些項目會一次執行一個。因此par::for_each(xs.chunks_mut(n), f)會就地寫入串列,每個工作者寫自己的部分,而多個串列的檢視可以用 zip 合成一個項目(pos.chunks_mut(n).zip(vel.chunks(n)))。若某個檢視的串列在建立檢視之後調整過大小(過時,2.9.7a),會在任何項目執行前觸發 panic。檢查會在物件標頭中標記項目觸及的每個集合型別(單一串列的項目約每個集合型別 15 ns,巢狀項目約每個集合型別 50 ns,主要是記憶體讀取;不含集合型別的項目沒有成本):對於大量小項目、每個工作量又很少的情況,這個成本可能超過工作本身。警告會說明應該改寫成什麼:讓每個項目擁有自己的值(共用的值在存入前先.clone())、凍結項目只會讀取的資料(xs.freeze(),2.9.7b),或透過檢查不會追蹤的其他Sync型別共用,或用chunks_mut分割串列。項目中的 future 以它的框架計算:持有同一個 future 的兩個項目也會一次執行一個。par不會移交它的項目,所以框架擷取了集合型別的 future 不能作為項目(編譯錯誤):請改把這類 future 當作任務啟動(2.18.1)。filter的結果與輸入共用項目。fold把輸入分成區塊,平行地 fold 每個區塊,再依序 foldinit與各區塊的結果。輸入為空時回傳init。reduce做同樣的事但沒有init,如同Iterator::reduce:輸入為空時回傳none(2.19.4)。- 在
scope內啟動的子工作會在 scope 結束時全部被 join。 par在與任務相同的工作竊取池上執行(2.18.3)。在par內等待的工作者會同時執行其他任務,因此在任務內呼叫par不會死結。傳給scope的Scope及其控制代碼如下:
struct Scope { /* list of jobs in the scope */ }
impl Scope {
fn spawn<T: Send>(self, f: fn() -> T + Send) -> ScopeHandle<T>;
}
struct ScopeHandle<T> { /* one spawned job */ }
impl<T> ScopeHandle<T> {
fn join(self) -> T; // waits until that job finishes
}
scope 結束時,也會等待每個尚未 join 的工作。
par::scope(|s| {
let left = s.spawn(|| sum_range(0, 500));
let right = s.spawn(|| sum_range(500, 1000));
println(f"{left.join() + right.join()}"); // join waits for that job
s.spawn(|| log("background")); // not joined; the scope waits for it at its end
});
#範例
use core::par::*;
let xs: List<i32> = (0..1000).collect();
par::for_each(xs, |x| { process(x) });
let squared: List<i32> = par::map(xs, |x| x * x);
let total: i32 = par::fold(squared, 0, |a, b| a + b);
let (a, b) = par::join(
|| compute_a(),
|| compute_b(),
);
par::scope(|s| {
for chunk in chunks {
s.spawn(|| process_chunk(chunk));
}
}); // ← every spawn is guaranteed complete at the end of the scope
#串列上的平行迴圈
這些函式接受任何 IntoIterator,所以大型串列上的平行迴圈是以串列的區塊作為項目來撰寫:每個工作者取得串列的一部分,而不是一次一個元素。多個工作者執行的閉包不能擷取串列(它不是 Sync);凍結的串列則可以。
// Read: the sum of 100M numbers, one chunk per item.
let parts = par::map(xs.chunks(1 << 16), |c| { let s = 0.0; for x in c { s += x; } s });
let total = parts.iter().sum();
// Write in place: each worker updates its own part.
par::for_each(xs.chunks_mut(1 << 16), |c| { for i in 0..c.len() { c[i] = c[i] * 2.0; } });
// Several lists of one length (an ECS system): zip their parts.
let items = pos.chunks_mut(4096).zip(vel.chunks(4096));
par::for_each(items, |(p, v)| { for i in 0..p.len() { p[i] = p[i] + v[i] * dt; } });
// Read-only data every item looks up: freeze it and capture it.
let table = table.freeze();
let out = par::map(queries, |q| table[q.slot]);
#2.19.2. par::for_each 與 Iterator
循序處理與平行處理以呼叫的形式區分。
xs.into_iter().for_each(f); // sequential (single thread)
par::for_each(xs, f); // parallel (worker pool)
工作以資料平行的方式按區塊分配,工作竊取排程器會自動平衡不均的工作負載。
#2.19.3. par::scope:結構化平行
par::scope 是可以動態啟動工作的結構化平行 API。
par::scope(|s| {
let h1 = s.spawn(|| task1());
let h2 = s.spawn(|| task2());
// results of h1, h2 are usable (inside the scope)
// joined automatically at the end of the scope
});
這遵循結構化並行的形式:scope 會阻塞,直到每個子 spawn 都完成。保留到其 par::scope 之後的 Scope 不能啟動工作:spawn 會觸發 panic,訊息為 Scope::spawn: the scope has ended; call spawninside the closure passed topar::scope``。
#par::try_scope:在第一個錯誤時取消
對於會擲回錯誤的子工作,使用 try_scope。
fn try_scope<E: Send>(f: fn(TryScope<E>) throws (E)) throws (E);
impl<E: Send> TryScope<E> {
fn spawn<T: Send>(self, f: fn() throws (E) -> T + Send) -> TryScopeHandle<T, E>;
fn is_cancelled(self) -> bool;
}
impl<T, E: Send> TryScopeHandle<T, E> {
fn join(self) throws (E) -> T; // its own error, or the scope's first error if cancelled before starting
}
若有一個子工作或主體 f 本身擲回錯誤,scope 就會被取消。尚未開始的子工作不會執行,已在執行的子工作會執行到完成。所有子工作結束後,try_scope 會重新擲回那第一個錯誤(來自 f 的錯誤會被攔截、取消 scope,並以相同方式重新擲回)。執行中的子工作可以檢查 is_cancelled() 以提早結束。
try par::try_scope(|s: par::TryScope<IoError>| {
let a = s.spawn(|| try load("a"));
let b = s.spawn(|| try load("b"));
use_both(try a.join(), try b.join());
});
#2.19.4. par::fold:必須滿足結合律
par::fold 與 par::reduce 的簽章如下;使用它們涉及一些數學條件。
fn fold<I: IntoIterator<Item = T>, T: Send>(iter: I, init: T, f: fn(T, T) -> T + Send + Sync) -> T;
fn reduce<I: IntoIterator<Item = T>, T: Send>(iter: I, f: fn(T, T) -> T + Send + Sync) -> T | none;
合併函式 f 必須滿足結合律,結果才會是確定的。reduce 不接受 init,沒有項目時回傳 none。init 最好是單位元:+ 為 0,* 為 1。對於不滿足結合律的函式,例如累加大數值的浮點數加總,結果可能不確定,需要特別留意。
let sum: i64 = par::fold(1..6, 0, |a, b| a + b); //→ 15
// floating-point: the result may differ slightly
let total: f64 = par::fold(values, 0.0, |a, b| a + b);
let max: i64 | none = par::reduce(scores, |a, b| a.max(b)); // none if scores is empty
#2.19.5. par::join:恰好兩個
用 par::join 並行執行兩個工作,並取得結果的配對。
let (a, b) = par::join(
|| expensive_computation_1(),
|| expensive_computation_2(),
);
兩個工作是最常見的 fork-join 形式,所以提供專用的函式。N 個工作請使用 par::for_each 或 par::scope。
#2.19.6. SIMD / GPU 整合
par 模組以 CPU 資料平行為中心:par::map 對每個項目呼叫一次 f,本身不套用 SIMD 多版本化(f 的程式碼與其他程式碼一樣,針對建置的 --target 及其基準 CPU 編譯,0.6.4)。GPU 加速不屬於標準函式庫;函式庫將透過後端介面使用它,預計在之後的版本推出。
par::map(xs, |x| heavy_op(x)); // CPU work-stealing
#2.19.7. 模組對應
各 API 的模組位置與內部策略:
| 項目 | 模組 | 策略 |
|---|---|---|
par::for_each | core::par | 區塊 + 工作竊取 |
par::map | core::par | 平行收集 |
par::fold | core::par | 樹狀歸約 |
par::reduce | core::par | 樹狀歸約,無 init |
par::filter | core::par | 平行判斷,再依序收集 |
par::join | core::par | 2 個任務的工作竊取 |
par::scope | core::par | spawn 控制代碼 + 自動 join |
par::try_scope | core::par | spawn 控制代碼 + 自動 join,在第一個錯誤時取消 |
內部實作是 task::spawn 之上的一層,共用同一個排程器。
發現錯誤? 在 GitHub 上編輯此頁 最後更新: