From 3e7505248c8cf9e4bd52efe1e6a8f955ce7a4d35 Mon Sep 17 00:00:00 2001 From: Mark Shinwell Date: Mon, 2 Sep 2024 13:36:27 +0100 Subject: [PATCH] Better fix for Unix Mutex usage (cherry picked from commit cbed7b3526eeda460b3d545424728a6559cd01b7) (cherry picked from commit f857b48ea65805097948b2f2d07bb80e3d14a9f4) --- ocaml/otherlibs/unix/unix_unix.ml | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/ocaml/otherlibs/unix/unix_unix.ml b/ocaml/otherlibs/unix/unix_unix.ml index b24875cfcce..172048b10d4 100644 --- a/ocaml/otherlibs/unix/unix_unix.ml +++ b/ocaml/otherlibs/unix/unix_unix.ml @@ -939,8 +939,29 @@ type popen_process = let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t) -(* CR ocaml 5 all-runtime5: remove lazy, which is here to stop: - "Must initialize systhreads library before using Mutex" *) +(* CR ocaml 5 all-runtime5: go back to the normal [Mutex]. *) + +module Mutex : sig + type t + val create : unit -> t + val protect : t -> (unit -> 'a) -> 'a +end = struct + type t = Mutex.t option + + external runtime5 : unit -> bool = "%runtime5" + + let create () = + (* On runtime4, systhreads must be linked to use [Mutex], which is + error-prone to ensure. The use of [Mutex] here is new in 5.2.0, so + we just omit it for runtime4, which doesn't have parallelism. *) + if runtime5 () then Some (Mutex.create ()) else None + + let protect t f = + match t with + | None -> f () + | Some mutex -> Mutex.protect mutex f +end + let popen_mutex = lazy (Mutex.create ()) let open_proc prog args envopt proc input output error =