1
我試圖在Rust裏面玩多線程,我碰到過一些我認爲很平凡的東西。下面的代碼片段:爲什麼我不能嘗試! Mutex.lock?
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let vec: Vec<i32> = vec!(1, 2, 3);
let shared = Arc::new(Mutex::new(vec));
let clone = shared.clone();
let join_handle = thread::spawn(move || {
let mut data = clone.lock().unwrap();
data.push(5);
});
join_handle.join().unwrap();
let clone = shared.clone();
let vec = try!(clone.lock());
println!("{:?}", *vec);
}
所以,我的問題是上線let vec = try!(clone.lock())
。這會導致以下編譯器錯誤:
error: mismatched types [E0308]
return $ crate :: result :: Result :: Err (
^
note: in this expansion of try! (defined in <std macros>)
help: run `rustc --explain E0308` to see a detailed explanation
note: expected type `()`
note: found type `std::result::Result<_, _>`
對我而言,這並沒有多大意義。 clone.lock()
返回TryLockResult<MutexGuard<T>>
,其實質上轉換爲Result<MutexGuard<T>, PoisonedError<MutexGuard<T>>
,這意味着try!(clone.lock())
應解析爲throw或MutexGuard<T>
。
我從根本上誤解了一些東西嗎?