Rust 书说原始指针“被认为是可发送的(如果它们的内容被认为是可发送的)”。
但是,从我所见,编译器在遇到指向 Sendable 类型的原始指针时会生成错误the trait
core::marker::Send is not implemented for the type
。
可能是我做错了什么,可能是文档不清楚,或者可能是错误消息无助于表明这段代码的真正问题是什么。
extern crate core;
use std::thread::Thread;
struct ShouldBeSendable {
x: i32
}
unsafe impl core::marker::Send for ShouldBeSendable { }
fn main() {
let sendablePtr : *const ShouldBeSendable = &ShouldBeSendable {x: 5};
let closure = move |:| {
*sendablePtr;
};
let something = Thread::spawn(closure);
}
产生错误:
test.rs:15:21: 15:34 error: the trait `core::marker::Send` is not implemented for the type `*const ShouldBeSendable` [E0277]
test.rs:15 let something = Thread::spawn(closure);
^~~~~~~~~~~~~
test.rs:15:21: 15:34 note: `*const ShouldBeSendable` cannot be sent between threads safely
test.rs:15 let something = Thread::spawn(closure);
^~~~~~~~~~~~~
error: aborting due to previous error
$ rustc --version
rustc 1.0.0-dev (d15192317 2015-01-25 16:09:48 +0000)
这最近发生了变化,使文档过时了。 感谢您注意到并提交错误!
@drewcrawford您可以使用Unique
包装器使您的原始指针Send
能够使用。 您的代码的此修改版本有效:
use std::ptr::Unique;
use std::thread::Thread;
#[derive(Copy)]
struct ShouldBeSendable {
x: i32
}
unsafe impl std::marker::Send for ShouldBeSendable { }
fn main() {
let ptr : *mut ShouldBeSendable = &mut ShouldBeSendable {x: 5}; // this is not `Send`
let sendablePtr = Unique(ptr); // but this is!
let closure = move |:| {
// `sendablePtr` con be moved inside this closure
let ptr = sendablePtr.0; // unpack the raw pointer
println!("{}", unsafe { (*ptr).x })
};
let something = Thread::scoped(closure).join();
}
使用NonNull
Rust 1.25 的@japaric示例。
https://play.rust-lang.org/?gist=1ce2532a0eefc60695663c26faddebe1&version=stable
最有用的评论
使用
NonNull
Rust 1.25 的@japaric示例。https://play.rust-lang.org/?gist=1ce2532a0eefc60695663c26faddebe1&version=stable