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 (13:36)
From: Benjamin Geer <ben@s...>
Subject: Re: [Caml-list] transactions?
skaller 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.

(* Implements try-with-finally. *)
let run_with_finally ~f ~(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. *)
ifdef THREADS then
   let run_in_mutex ~f ~(mutex : Mutex.t) =
     Mutex.lock mutex;
     run_with_finally ~f ~finally:(function () -> Mutex.unlock mutex) ;;

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

(* Calls a function, using the supplied mutex if threads are enabled. *)
let run_in_optional_mutex ~f ~mutex =
   (ifdef THREADS then
      run_in_mutex ~f ~mutex
      f ()) ;;

Example usage:

let hash_mutex = create_optional_mutex () ;;

let add_to_hash h k v =
     ~f:(function () ->
         if Hashtbl.mem h k then () else Hashtbl.add h k v)
     ~mutex:hash_mutex ;;


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