From b7d4dcf3a6a741ba85119b45a786a55e70bb910e Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Tue, 23 Feb 2021 21:30:54 +0900 Subject: [PATCH] Make vm_exit_handler installation MT-safe --- win32/win32.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/win32/win32.c b/win32/win32.c index 90e109d5a0..e2d4cceeb3 100644 --- a/win32/win32.c +++ b/win32/win32.c @@ -781,15 +781,23 @@ vm_exit_handler(ruby_vm_t *vm) LeaveCriticalSection(&conlist_mutex); } +#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval)) + /* License: Ruby's */ static void install_vm_exit_handler(void) { - static bool installed = 0; + static LONG installed = 0; + LONG i; - if (!installed) { + while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) { + if (i != 0) { + Sleep(1); + continue; + } ruby_vm_at_exit(vm_exit_handler); - installed = 1; + ATOMIC_LONG_CAS(installed, -1, 1); + break; } }