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
Problem with try_lock on win32.
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2010-01-27 (08:23)
From: David Allsopp <dra-news@m...>
Subject: RE: [Caml-list] Problem with try_lock on win32.
Romain Beauxis:
> I have a problem with the following code under win32:
> let m = Mutex.create ()
> let () =
>   Mutex.lock m;
>   if Mutex.try_lock m then
>     Printf.printf "locked !\n"
>   else
>     Printf.printf "could not lock!\n"

This code is behaving correctly for a Windows mutex (AFAIK - I can't find
the relevant bit in the Synchronisation on MSDN atm) - once a thread has
locked a Windows mutex, WaitForSingleObject will return WAIT_OBJECT_0 (i.e.
success) because for that thread the mutex is signalled (it's only other
threads which will see the object as non-signalled). I guess it's a
philosophical discussion for whether it's useful for a thread to be able to
block itself permanently by trying to lock a mutex which it has already
locked (the POSIX way).

One possible fix to make it behave like POSIX would be to patch
otherlibs/systhreads/win32.c so that caml_mutex_lock records the thread ID
of the thread when it locks the mutex. Some trick would be required to block
the thread (permanently) if it calls Mutex.lock twice (to match the POSIX
behaviour). caml_mutex_try_lock can check the thread ID before using
WaitForSingleObject and return false if it shows that it's locked and
caml_mutex_unlock would clear the thread ID to null on a successful release.
Two potential problems (which I'm guessing other Windows users on the list
may comment on, if relevant):

a) The representation of a mutex internally (the abstract value) changes
which means that any Windows C stubs which interoperate with OCaml mutexes
would break.
b) The behaviour of Mutex.lock and Mutex.try_lock under Windows would be
altered to be non-Windows-like behaviour which may affect existing
Windows-only programs which rely on it.

But you could raise it as a bug in Mantis just for cross-platform
consistency of the Mutex module (another option would be to have a separate
module PosixMutex with the guaranteed consistent semantics and leave the
Mutex module as behaving in an OS-specific way)