English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] transactions?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2004-05-02 (14:59)
From: Benjamin Geer <ben@s...>
Subject: Re: [Caml-list] transactions?
Benjamin Geer wrote:
>> Is there an Ocaml eqivalent of begin/end blocking section?
>> I.e. something that sets the global lock if threads
>> are enabled (but still compiles if they're not)?
> You can use camlp4's pa_ifdef.cmo to create a global mutex only if 
> threads are enabled.  The utility functions below take care of this, as 
> well as unlocking the mutex if an exception is thrown.

Actually I've just realised that pa_ifdef.cmo seems to be deprecated 
(it's not mentioned in the camlp4 docs anymore), but you can use 
pa_macro.cmo[1].  Here's a revised version:

(* Implements try-with-finally. *)
let try_with_finally ~(f : unit -> 'a) ~(finally: unit -> unit) =
   let res =
       f ()
     with e ->
       finally ();
       raise e
     finally ();
     res ;;

(* Locks a mutex, calls a function, then unlocks the mutex.  The mutex
    is also unlocked if the function throws an exception. *)
   let call_in_mutex ~f ~(mutex : Mutex.t) =
     Mutex.lock mutex;
     try_with_finally ~f ~finally:(function () -> Mutex.unlock mutex) END ;;

(* If threads are enabled, creates a mutex, otherwise returns unit. *)
let create_optional_mutex () =
      Mutex.create ()
      () END) ;;

(* This function's arguments are a function to be called, and a value
    returned by create_optional_mutex.  If threads are enabled, it
    calls the function in a mutex.  If threads are disabled, it
    just calls the function. *)
let call_in_optional_mutex ~f ~mutex =
      call_in_mutex ~f ~mutex
      f () END) ;;

Note that you have to take care of defining the THREADS symbol.


[1] http://caml.inria.fr/camlp4/manual/manual002.html#toc1

To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners