Threads and atomicity of reading and assignement

Hi,

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)?

1 Like

Hello,

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).

For more about the case of Multicore OCaml you can take a look at Section 9 of the paper https://kcsrk.info/papers/pldi18-memory.pdf.

Cheers,
Nicolas

2 Likes

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…

It’s probably a good idea to use the Atomic module now for mutable values to be forward-compatible with multicore OCaml.

thanks for the advice. I’ll make sure I use Atomic as soon as I require ocaml >= 4.12. For the moment I’m trying to stay compatible with 4.08