Unsafe raw pointer in std::thread

Did anything change in Rust to make this stop working?

I pasted in the unsafe code and got this error:
*mut [T] cannot be sent between threads safely`

I'm working on a threaded sort and expect to need unsafe and raw pointers, and anyway, I'd like to figure out how to use them. At this stage I'm simply trying to pass the pointer to multiple threads, but I get either cannot share or cannot be sent in all the things I've tried.

I also found How to share a raw pointer between threads? but I'm not sure the solution applies - the thread closure doesn't take arguments.

Did anything change in Rust to make this stop working?

Yes and no. The code will still compile, but only if you set the edition of it (in Cargo.toml) to 2018 or older. The 2021 edition introduced Disjoint capture in closures - The Rust Edition Guide which causes the RawSend wrapper to be defeated, because

            threaded_quicksort(&mut *collection_1.0);

is considered to capture the field value collection_1.0 (which has the raw pointer type) instead of the RawSend wrapper. You can solve this problem within the 2021 edition by introducing an extra let that forces the RawSend to be captured as a whole:

        let thread = std::thread::spawn(move || {
            let collection_1 = collection_1;
            threaded_quicksort(&mut *collection_1.0);
        });
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.