#E0085: 스레드를 넘을 수 없는 값
값을 두 스레드가 동시에 쓸 수 있습니다. Sync가 아닌 타입의 static, 스레드로 보낸 클로저의 [ref x] 캡처, task에 준 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에서 이 페이지 고치기. 마지막 수정