Rust: core :: marcador :: Enviar e ponteiros brutos

Criado em 28 jan. 2015  ·  3Comentários  ·  Fonte: rust-lang/rust

O livro Rust diz que os ponteiros brutos "são considerados remetíveis (se seu conteúdo for considerado remetível)".

No entanto, pelo que posso ver, o compilador gera o erro the trait core :: marker :: Send is not implemented for the type quando encontra um ponteiro bruto para um tipo Sendable.

Pode ser que eu esteja fazendo algo errado, pode ser que a documentação não esteja clara ou pode ser que a mensagem de erro não seja útil para indicar qualquer que seja o verdadeiro problema com este código.

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);
}

Produz um erro:

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)

Comentários muito úteis

Todos 3 comentários

Isso mudou recentemente, deixando os documentos desatualizados. Obrigado por notar e preencher um bug!

@drewcrawford Você pode usar o Unique wrapper para tornar seu ponteiro bruto Send capaz. Esta versão modificada do seu código funciona:

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();
}
Esta página foi útil?
0 / 5 - 0 avaliações