生锈.UnsafeCell线程安全



我使用的对象从一个板条箱,这不是由我写的,我有一个结构,我想使用作为一个全局变量,但我得到这个错误:

error[E0277]: `Rc<UnsafeCell<UnicornInner<'static, ()>>>` cannot be sent between threads safely
--> srcmain.rs:76:37
|
76 | fn init_emulator(emulator_instance: State<EmulatorGlobal>) {
|                                     ^^^^^^^^^^^^^^^^^^^^^ `Rc<UnsafeCell<UnicornInner<'static, ()>>>` cannot be sent between threads safely
|
= help: within `Unicorn<'static, ()>`, the trait `Send` is not implemented for `Rc<UnsafeCell<UnicornInner<'static, ()>>>`
= note: required because it appears within the type `Unicorn<'static, ()>`
= note: required for `std::sync::Mutex<Unicorn<'static, ()>>` to implement `Send`
note: required because it appears within the type `EmulatorGlobal`
--> srcmain.rs:27:8
|
27 | struct EmulatorGlobal(Mutex<Unicorn<'static, ()>>);
|        ^^^^^^^^^^^^^^
note: required by a bound in `State`
--> C:UsersAslan.cargoregistrysrcgithub.com-1ecc6299db9ec823tauri-1.2.2srcstate.rs:14:25
|
14 | pub struct State<'r, T: Send + Sync + 'static>(&'r T);
|                         ^^^^ required by this bound in `State`

我猜这个问题是由于使用了"unsafecell"导致的。我想知道是否有一种合适而简单的方法来"monkeypatch"。这段代码保证了整个项目的安全。下面是结构体的代码:

/// A Unicorn emulator instance.
pub struct Unicorn<'a, D: 'a> {
inner: Rc<UnsafeCell<UnicornInner<'a, D>>>,
}

感谢您的帮助。

我正在用金牛座写一个应用程序,所以我定义了变量如下:

struct EmulatorGlobal(Mutex<Unicorn<'static, ()>>);
下面是它在代码 中的用法
#[tauri::command]
fn init_emulator(emulator_instance: State<EmulatorGlobal>) {
let mut unicorn: Unicorn<()> = Unicorn::new(Arch::X86, Mode::MODE_64).expect("ERROR");
}

模拟器的板条箱

乌利希期刊指南:该结构体使用的不是std::rc:: rc,而是alloc::rc:: rc(不确定它们是否不同,但根据文档,它们看起来很相似)。(感谢@erikkallen的提醒)

结构体定义

您的问题的核心是如何将unicorn_engine::Unicorn存储在static变量中(或用于基于您的错误约束为Send的类型),答案是您不能。

当错误泄漏时,它在内部使用一个不线程安全的Rc。任何尝试"monkeypatch";它进入工作将是不健全

在多线程系统中使用非线程安全类型的一个解决方法是创建一个线程来保存和操作该对象,并使用通道将操作和/或结果传递给系统的其余部分。虽然特别考虑这种类型,但根据您正在做的事情,它可能非常乏味。

我不是Rust专家,但我很确定如果你在线程之间发送它,你需要一个Arc而不是Rc。

最新更新