简体   繁体   English

如何将指针发送到另一个线程?

[英]How to send a pointer to another thread?

I created a Rust wrapper for a C++ library for a camera using bindgen , and the camera handle in the C++ library is defined as typedef void camera_handle which bindgen ported over as:我为使用bindgen的相机创建了 C++ 库的 Rust 包装器,并在 C++ 库中定义为typedef void camera_handle库中的相机句柄

pub type camera_handle = ::std::os::raw::c_void;

I'm able to successfully connect to the camera and take images, however I wanted to run code on a separate thread for temperature control of the camera, essentially changing the cooler power based on the current temperature of the camera, which I want to have run separately from the rest of the code.我能够成功连接到相机并拍摄图像,但是我想在一个单独的线程上运行代码来控制相机的温度,本质上是根据我想要的相机的当前温度来改变冷却器的功率与代码的 rest 分开运行。 These calls require the camera handle, but when I spawn a new thread, I keep getting the error:这些调用需要相机句柄,但是当我生成一个新线程时,我不断收到错误消息:

'*mut std::ffi::c_void' cannot be sent between threads safely

And underneath it, it mentions:在它下面,它提到:

the trait 'std::marker::Send' is not implemented for '*mut std::ffi::c_void'

How can I send this to another thread so I can use this camera handle there as well?我怎样才能将它发送到另一个线程,以便我也可以在那里使用这个相机手柄? I have tried using fragile and send_wrapper , but have been unsuccessful with both of them.我曾尝试使用脆弱send_wrapper ,但都没有成功。

Pointers do not implement Send or Sync since their safety escapes the compiler.指针不实现SendSync ,因为它们的安全性逃脱了编译器。 You are intended to explicitly indicate when a pointer is safe to use across threads.您打算明确指示何时可以安全地跨线程使用指针。 This is typically done via a wrapper type that you implement Send and/or Sync on yourself:这通常是通过您自己实现Send和/或Sync的包装器类型来完成的:

struct CameraHandle(*mut c_void);

unsafe impl Send for CameraHandle {}
unsafe impl Sync for CameraHandle {}

Since implementing these traits manually is unsafe , you should be extra diligent to ensure that the types from the external library actually can be moved another thread ( Send ) and/or can be shared by multiple threads ( Sync ).由于手动实现这些特征是unsafe的,因此您应该格外努力以确保外部库中的类型实际上可以移动到另一个线程( Send )和/或可以由多个线程( Sync )共享。

If you ever take advantage of the pointer's mutability without the protection of &mut self , it should probably not be Sync since having two &mut T at the same time is always unsound.如果您在没有&mut self保护的情况下利用指针的可变性,它可能应该是Sync因为同时拥有两个&mut T总是不合理的。

See:看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM