Mutate from multiple threads without interior mutability?

They don't! &File (shared reference to a File) implements Read and Write, so you can easily "mutate" a File concurrently without interior mutability:

let file = /* get a `File` somehow */;
let file_ref = &file;
crossbeam::scope(|s| {
    s.spawn(|_| {
        let mut buf = [0; 100];
        let _ = file_ref.read_exact(&mut buf);
    });
    s.spawn(|_| {
        let mut buf = [1, 2, 3, 4, 5];
        let _ = file_ref.write_all(&buf);
    });
});

[edit: those should be move closures and the declaration of file_ref should read let mut file_ref = &file;, thanks @parasyte]

Or to put it another way, File has built-in interior mutability, implemented by the OS and not by the standard library.

1 Like