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
Unix.localtime not threadsafe?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-09-03 (07:54)
From: Xavier Leroy <Xavier.Leroy@i...>
Subject: Re: [Caml-list] Unix.localtime not threadsafe?
> I was looking at the Unix.localtime implementation, and it appears to
> me that it's not threadsafe.  I'm wondering if anyone can confirm.
> First off, the underlying localtime call is definitely not re-entrant.
> The tm data structure is shared among all calls, leading to the
> possibility of races.

As others mentioned, the C library implementation of this function
could use thread-local storage to avoid this particular race.  I don't
think this is guaranteed, though.

> If I understand the way ocaml's locking works, another thread could
> make a call to localtime where alloc_small is called.

No, at least not another Caml thread: GC triggered from C code
(e.g. alloc_small()) cannot cause context switches.  So, from a Caml
standpoint, the call to localtime() and the following allocation of
its result are atomic.

> If there are mixed C threads and Ocaml threads, then a call by the C
> thread at that point could muck up the tm data structure before
> switching back to OCaml, thus leading to bad data getting into the
> tm data structure.

Yes, this is possible in principle if 1- some non-Caml threads call
localtime(), and 2- the implementation of that function does not use
thread-local storage.

- Xavier Leroy