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 上编辑此页 最后更新: