Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Philippe Wang <>
Subject: Re: [Caml-list] threads

>  let x = Array.make 100 []
>  let update i n = x.(i) <- n :: x.(i)
>  let read i = x.(i)

I don't think you can obtain funny results when you don't put a mutex
on these two specific "update" and "read".
What is sure is that "update" function is not atomic because you have
a value allocation at the right of "<-" (with :: operator), and this
may trigger garbage collection and/or make the scheduler change the
running thread.

What you can be sure with the current official OCaml distribution is
that there won't be at the exact same time both an (<-)operation and a
But it is actually possible, for instance, for a thread to compute
while another one is simultaneously writing on a socket. So it is
generally not a good idea to count on some operation atomicity to put
or not a mutex lock (well it's good to write some hard-to-debug


Philippe Wang

On Tue, Sep 8, 2009 at 7:33 PM, ygrek <> wrote:
> Hello,
>  let x = Array.make 100 []
>  let update i n = x.(i) <- n :: x.(i)
>  let read i = x.(i)
>  Consider the following scenario: one thread is `update`ing x, another
> thread(s) uses only `read`. Is it safe to use these functions without
> locking on mutex?
>  I.e. is Array.set atomic? What about updating references (:=) ?
>  If I understand correctly these operations require only one cpu
> instruction to update one machine word and so should be atomic. Taking
> into account "single-cpu affinity" of ocaml program it should be safe
> to write such multithreaded code. Is it true?
>  Is it safe to assume that ocamlopt won't skip reads/writes to globally
> visible memory address using cached value in a register?
> --
>  ygrek
> _______________________________________________
> Caml-list mailing list. Subscription management:
> Archives:
> Beginner's list:
> Bug reports:

Philippe Wang