fnmain() { letmut data = 233; crossbeam::scope(|s| { s.spawn(|_| { data += 1; }); }).unwrap(); println!("{}", data); }
输出:
234
这里只可变借用(mutable
borrow)了一次,所以编译可以通过。但是如果可变借用多次呢?
use crossbeam; use std::sync::Mutex;
fnmain() { letmut data = 233; crossbeam::scope(|s| { s.spawn(|_| { data += 1; }); s.spawn(|_| { data += 1; }); }).unwrap(); println!("{}", data); }
这时就会编译错误:
error[E0499]: cannot borrow `data` as mutable more than once at a time --> src/main.rs:18:17 | 15 | s.spawn(|_| { | --- first mutable borrow occurs here 16 | data += 1; | ---- first borrow occurs due to use of `data` in closure 17 | }); 18 | s.spawn(|_| { | ----- ^^^ second mutable borrow occurs here | | | first borrow later used by call 19 | data += 1; | ---- second borrow occurs due to use of `data` in closure
error: aborting due to previous error
For more information about this error, try `rustc --explain E0499`. error: could not compile `scoped_thread`
To learn more, run the command again with --verbose.