Is `mem :: swap`ing` Mutex <T>` really safe?

A simple example:

use std::mem;
use std::sync::{Mutex};

fn main() {
    let mut orig = Mutex::new(vec![1, 2, 3]);
    let mut other = Mutex::new(vec![]);
    mem::swap(&mut orig, &mut other);
    println!("{:?}", other);
}

This program, according to Rust, is completely safe. However, the implementation swap(or replace) is not trying to block anything. From source:

#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap<T>(x: &mut T, y: &mut T) {
    unsafe {
        // Give ourselves some scratch space to work with
        let mut t: T = uninitialized();

        // Perform the swap, `&mut` pointers never alias
        ptr::copy_nonoverlapping(&*x, &mut t, 1);
        ptr::copy_nonoverlapping(&*y, x, 1);
        ptr::copy_nonoverlapping(&t, y, 1);

        // y and t now point to the same thing, but we need to completely
        // forget `t` because we do not want to run the destructor for `T`
        // on its value, which is still owned somewhere outside this function.
        forget(t);
    }
}

Using unsynchronized access in variables Mutexor Atomicseems like a recipe for problems, is it just as safe? And if so, why?

+4
source share
2 answers

Mutex Sync, , . , (Arc, ), , , , Sync, .

Rust. , mut , . , , . Arc , mut pointee; mut. Mutex::lock &self: mut. , Atomic*::store &self. static mut , , , .

mem::swap mut. Mutex swap, , - Arc, static (not mut) static mut ( ).

, swap , .

+5

: Mutability XOR Aliasing.

mem::swap , , ?

&mut T T .


, a Mutex AtomicXXX (AtomicXXX) "Mutability XOR Aliasing" (Mutex) , .

:

  • (&mut T T)
  • ,

, , mem::swap mem::replace, , , , aliasing , - .

+3

All Articles