Rust: core :: marker :: Sendおよびrawポインター

作成日 2015年01月28日  ·  3コメント  ·  ソース: rust-lang/rust

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)

最も参考になるコメント

全てのコメント3件

これは最近変更され、ドキュメントは古くなっています。 バグに気づいて提出してくれてありがとう!

@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();
}
このページは役に立ちましたか?
0 / 5 - 0 評価