Multithread read/write

Suppose I have two threads A and B and a shared piece of data V that is very large (Say a vector with 1 billion entries or something). The point is, that writing data to V can take a long time.

Data-structure V is mutable in A, but not in B, but B can read the content of V.

Is this well defined in rust?

Consider the case where some function in A changes the contend of V. Remember that this will take some time. Say a minute or so… At the same time B reads (or copies, doesn’t matter) the contend of V.

This access of B on V is undefined, right? It might capture data from V that is partly rewritten, partly not.

Or do I miss the point her?

Yes, the only safe way to do this is to surround access to it by a lock, (e.g. a RwLock).

I realize this may be a hypothetical scenario, but if you really were trying to do something like this, I would recommend against a plain-old Vec – you probably want something that can keep a transaction log with fast atomic updates so your reader doesn’t need to wait a minute for the writer to finish one of its changes.

Yes, it's defined to be impossible. Data can be either shared and read-only for everyone, or locked for exclusive read-write access from one place only. You can't have both on one piece of data at the same time.

There are higher-level constructs like Mutex/RwLock, RefCell, Cell/Atomic* that bend the rules and give more flexibility at cost of some overhead or other restrictions.

For vector there's split_at_mut() which gives two disjoint slices. In that case you can send one slice to one thread, and other slice to another thread, because the function guarantees there's no overlap between them, so there's no risk of mutable aliasing.

1 Like

Yes, it’s defined to be impossible. Data can be either shared and read-only for everyone, or locked for exclusive read-write access from one place only. You can’t have both on one piece of data at the same time.

I see. That was actually was I was looking for. Will a situation, like the one I described, be catched by the compiler, in any case or will it result in a run time error? I think it is impossible for a compiler to determine, if something like this happens. Or mybe I’m still to much in the “C” thinking.

I’m confused. Doesn’t your answer contradict the one given by kornel?

And the vector was just used to come up with an example…