Today I've stumbled upon the curious behaviour of the Rust compiler. I want to send a pointer to another thread. Raw pointers aren't Send
. A common way to circumvent that restriction is to define a wrapper type and implement Send
for it. However, I think Rust decided it would no longer tolerate this chicanery, at least in some cases
Here's the simple code snippet demonstrating the newfound strictness of the compiler (playground):
struct Wrapper(*mut ());
unsafe impl Send for Wrapper {}
extern "C" {
fn foo() -> *mut ();
fn bar(ptr: *mut ());
}
fn main() {
let ptr = foo();
// This closure compiles w/o any problems...
std::thread::spawn({
let ptr = Wrapper(ptr);
move || {
baz(ptr);
}
});
// ...but in this one the compiler sees that I'm trying to trick it and
// produces an error :)
std::thread::spawn({
let ptr = Wrapper(ptr);
move || {
let Wrapper(ptr) = ptr;
bar(ptr);
}
});
}
fn baz(ptr: Wrapper) {
let Wrapper(ptr) = ptr;
bar(ptr);
}
Have I stumbled into a bug, or is there an explanation?