[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| 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 =
try
f ()
with e ->
finally ();
raise e
in
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 ()
else
()) ;;
(* 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
else
f ()) ;;
---------------------------------------------------------------------
Example usage:
---------------------------------------------------------------------
let hash_mutex = create_optional_mutex () ;;
let add_to_hash h k v =
run_in_optional_mutex
~f:(function () ->
if Hashtbl.mem h k then () else Hashtbl.add h k v)
~mutex:hash_mutex ;;
---------------------------------------------------------------------
Ben
-------------------
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