docs

You are reading the docs for v0.1.0. Nabi 0.1.0 is no longer supported. Latest release: v0.1.3 →

#E0085: value cannot cross threads

The value may be used by two threads at once: a static of a non-Sync type, a [ref x] capture in a spawned closure, or a non-Send value given to a task. Share it through a Mutex, an atomic or a channel.

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

Share the counter through an atomic:

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

Chapter 12 shows the other ways to share state between threads.

Related: E0058 invalid closure capture, E0107 shared value handed over

Found a mistake? Edit this page on GitHub. Last updated