我無法在 Rust 線??程之間發送非空型別。我需要在 Windows rust API 的 NonNull 指標上呼叫一個方法。
我已經嘗試過 Arc<Mutex< NonNull>> 和 Arc<Mutex<RefCell<Box< NonNull>>> 但找不到發送和同步 NonNull 的方法。
我希望執行緒停止并等待互斥鎖,因此呼叫方法或什至改變 NonNull 型別不應該是執行緒問題,但即使使用運行時借用檢查,我也會收到錯誤:'NonNull<c_void> 無法在執行緒之間安全發送'然后是一個串列:
由于對“發送”的實作的要求而需要
..等等。
我即將嘗試將方法作為 dyn 傳遞,但這應該是可能的,對嗎?
uj5u.com熱心網友回復:
您需要提供一個不安全的實作Send來通知編譯器您已經考慮了指標后面物件的執行緒安全性(您這樣做了,因為您想使用互斥鎖進行同步)。例如:
// Wrapper around `NonNull<RawType>` that just implements `Send`
struct WrappedPointer(NonNull<RawType>);
unsafe impl Send for WrappedPointer {}
// Safe wrapper around `WrappedPointer` that gives access to the pointer
// only with the mutex locked.
struct SafeType {
inner: Mutex<WrappedPointer>,
}
impl SafeType {
fn some_method(&self) {
let locked = self.inner.lock();
// use ptr in `locked` to implement functionality, but don't return it
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370768.html
