I have a mutable variable v of record type (type t = { mutable data : x } where x is some more or less complex type), and I want to access it via two concurrent threads. My question is: it is safe (in the sense of non-corruptable data) to read (or write) the variable v, or should I protect reading/writing with a mutex? In other words, is reading or writing (or both) an atomic operation?
In other words, suppose thread 1 wants to read the value v.data, while thread 2 is writing a new value. Am I certain that thread 1 will read either the old or the new value, or is this possible that the read occurs before the writing is finished, resulting to a pointer value with some bytes from the old value and some bytes from the new one (and hence pointing to a random place in memory)?
If you are thinking of this question in the context of current OCaml, I believe there is no issue because the global runtime lock means that the two threads will not run in parallel, and reading (and writing) to the ref cell behave like atomic operations effectively. In the case of Multicore OCaml I believe the memory model guarantees that thread 1 will read either the old or the new value, and not something else (“out-of-thin-air” safety).
yes, the question (currently) is for current ocaml, but I do hope my library will be portable to Multicore soon!
Thanks a lot for the answer. I will remove my Mutexes…