docs

#E0085: 無法跨執行緒的值

這個值可能同時被兩個執行緒使用:非 Sync 型別的 static、產生執行緒的閉包中的 [ref x] 擷取,或交給任務的非 Send 值。請透過 Mutex、原子型別或通道共用它。

nabi
use std::thread;

let count = 0;
let t = thread::spawn([ref count] || { count += 1; });
try! t.join();
error[E0085]: `[ref count]` can't be used in a closure that may run on another thread: both threads could change `count` at once
  --> main.nabi:4:9
   |
 4 | let t = thread::spawn([ref count] || { count += 1; });
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: write `let count = Atomic::new(count);` before the closure, capture `count` without `ref`, and use `count.load()` / `count.store(..)`; or return the value from the closure instead

透過原子型別共用計數器:

nabi
use std::thread;

let count = Atomic::new(0);
let t = thread::spawn(|| { count.fetch_add(1); });
try! t.join();
println(f"{count.load()}");
1

第 12 章介紹了在執行緒之間共用狀態的其他方式。

相關錯誤碼:E0058 無效的閉包擷取、E0107 移交了共用的值

發現錯誤? 在 GitHub 上編輯此頁 最後更新: