From f088441e35fcac532df6c986903e420be9073edd Mon Sep 17 00:00:00 2001 From: Mark Elvers Date: Sun, 1 Mar 2026 08:44:51 +0000 Subject: [PATCH 1/2] Fix pool_mutex initialization order on Windows Move initialize_threading() to run before pool_mutex is accessed in lwt_unix_start_job, rather than only inside the DETACH/SWITCH case. On Windows, CRITICAL_SECTION must be explicitly initialized via InitializeCriticalSection before use. Unlike pthreads where a zero-initialized mutex (PTHREAD_MUTEX_INITIALIZER) is valid, a zero-initialized CRITICAL_SECTION is invalid. The previous code could access pool_mutex before initialize_threading() was called, causing crashes or undefined behavior on Windows when the first job used async_method != NONE. initialize_threading() is idempotent (guarded by threading_initialized flag), so calling it earlier is safe and has no effect on Unix platforms. --- src/unix/lwt_unix_stubs.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/unix/lwt_unix_stubs.c b/src/unix/lwt_unix_stubs.c index d77237a4c..83a21a2e4 100644 --- a/src/unix/lwt_unix_stubs.c +++ b/src/unix/lwt_unix_stubs.c @@ -1063,6 +1063,13 @@ CAMLprim value lwt_unix_start_job(value val_job, value val_async_method) { lwt_unix_async_method async_method = Int_val(val_async_method); int done = 0; + /* Ensure threading is initialized before using pool_mutex. + On Windows, CRITICAL_SECTION must be initialized before use; + unlike pthreads, zero-initialized CRITICAL_SECTIONs are invalid. */ + if (async_method != LWT_UNIX_ASYNC_METHOD_NONE) { + initialize_threading(); + } + /* Fallback to synchronous call if there is no worker available and we can not launch more threads. */ if (async_method != LWT_UNIX_ASYNC_METHOD_NONE) { @@ -1087,8 +1094,6 @@ CAMLprim value lwt_unix_start_job(value val_job, value val_async_method) { case LWT_UNIX_ASYNC_METHOD_DETACH: case LWT_UNIX_ASYNC_METHOD_SWITCH: - initialize_threading(); - lwt_unix_mutex_init(&job->mutex); lwt_unix_mutex_lock(&pool_mutex); From 3d413028b9dad89377f672414479ed090eafb639 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Proust?= Date: Mon, 20 Apr 2026 15:53:21 +0200 Subject: [PATCH 2/2] CHANGES --- CHANGES | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES b/CHANGES index a6d415fa7..096e1c1fd 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,9 @@ +===== 6.1.2 ===== + +====== Fixes ====== + + * fix initialisation of lock on Windows. (Mark Elvers, David Allsopp, #1103, #1107, #1104) + ===== 6.1.1 ===== ====== Fixes ======