1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gthread.c: solaris thread system implementation
5 * Copyright 1998-2001 Sebastian Wilhelmi; University of Karlsruhe
6 * Copyright 2001 Hans Breuer
8 * SPDX-License-Identifier: LGPL-2.1-or-later
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
25 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
26 * file for a list of people on the GLib Team. See the ChangeLog
27 * files for a list of changes. These files are distributed with
28 * GLib at ftp://ftp.gtk.org/pub/gtk/.
31 /* The GMutex and GCond implementations in this file are some of the
32 * lowest-level code in GLib. All other parts of GLib (messages,
33 * memory, slices, etc) assume that they can freely use these facilities
34 * without risking recursion.
36 * As such, these functions are NOT permitted to call any other part of
39 * The thread manipulation functions (create, exit, join, etc.) have
40 * more freedom -- they can do as they please.
46 #include "glib-init.h"
48 #include "gthreadprivate.h"
58 g_thread_abort (gint status,
59 const gchar *function)
61 fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s. Aborting.\n",
62 strerror (status), function);
66 /* Starting with Vista and Windows 2008, we have access to the
67 * CONDITION_VARIABLE and SRWLock primitives on Windows, which are
68 * pretty reasonable approximations of the primitives specified in
69 * POSIX 2001 (pthread_cond_t and pthread_mutex_t respectively).
71 * Both of these types are structs containing a single pointer. That
72 * pointer is used as an atomic bitfield to support user-space mutexes
73 * that only get the kernel involved in cases of contention (similar
74 * to how futex()-based mutexes work on Linux). The biggest advantage
75 * of these new types is that they can be statically initialised to
76 * zero. That means that they are completely ABI compatible with our
77 * GMutex and GCond APIs.
82 g_mutex_init (GMutex *mutex)
84 InitializeSRWLock ((gpointer) mutex);
88 g_mutex_clear (GMutex *mutex)
93 g_mutex_lock (GMutex *mutex)
95 AcquireSRWLockExclusive ((gpointer) mutex);
99 g_mutex_trylock (GMutex *mutex)
101 return TryAcquireSRWLockExclusive ((gpointer) mutex);
105 g_mutex_unlock (GMutex *mutex)
107 ReleaseSRWLockExclusive ((gpointer) mutex);
112 static CRITICAL_SECTION *
113 g_rec_mutex_impl_new (void)
115 CRITICAL_SECTION *cs;
117 cs = g_slice_new (CRITICAL_SECTION);
118 InitializeCriticalSection (cs);
124 g_rec_mutex_impl_free (CRITICAL_SECTION *cs)
126 DeleteCriticalSection (cs);
127 g_slice_free (CRITICAL_SECTION, cs);
130 static CRITICAL_SECTION *
131 g_rec_mutex_get_impl (GRecMutex *mutex)
133 CRITICAL_SECTION *impl = mutex->p;
135 if G_UNLIKELY (mutex->p == NULL)
137 impl = g_rec_mutex_impl_new ();
138 if (InterlockedCompareExchangePointer (&mutex->p, impl, NULL) != NULL)
139 g_rec_mutex_impl_free (impl);
147 g_rec_mutex_init (GRecMutex *mutex)
149 mutex->p = g_rec_mutex_impl_new ();
153 g_rec_mutex_clear (GRecMutex *mutex)
155 g_rec_mutex_impl_free (mutex->p);
159 g_rec_mutex_lock (GRecMutex *mutex)
161 EnterCriticalSection (g_rec_mutex_get_impl (mutex));
165 g_rec_mutex_unlock (GRecMutex *mutex)
167 LeaveCriticalSection (mutex->p);
171 g_rec_mutex_trylock (GRecMutex *mutex)
173 return TryEnterCriticalSection (g_rec_mutex_get_impl (mutex));
179 g_rw_lock_init (GRWLock *lock)
181 InitializeSRWLock ((gpointer) lock);
185 g_rw_lock_clear (GRWLock *lock)
190 g_rw_lock_writer_lock (GRWLock *lock)
192 AcquireSRWLockExclusive ((gpointer) lock);
196 g_rw_lock_writer_trylock (GRWLock *lock)
198 return TryAcquireSRWLockExclusive ((gpointer) lock);
202 g_rw_lock_writer_unlock (GRWLock *lock)
204 ReleaseSRWLockExclusive ((gpointer) lock);
208 g_rw_lock_reader_lock (GRWLock *lock)
210 AcquireSRWLockShared ((gpointer) lock);
214 g_rw_lock_reader_trylock (GRWLock *lock)
216 return TryAcquireSRWLockShared ((gpointer) lock);
220 g_rw_lock_reader_unlock (GRWLock *lock)
222 ReleaseSRWLockShared ((gpointer) lock);
227 g_cond_init (GCond *cond)
229 InitializeConditionVariable ((gpointer) cond);
233 g_cond_clear (GCond *cond)
238 g_cond_signal (GCond *cond)
240 WakeConditionVariable ((gpointer) cond);
244 g_cond_broadcast (GCond *cond)
246 WakeAllConditionVariable ((gpointer) cond);
250 g_cond_wait (GCond *cond,
251 GMutex *entered_mutex)
253 SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, INFINITE, 0);
257 g_cond_wait_until (GCond *cond,
258 GMutex *entered_mutex,
261 gint64 span, start_time;
265 start_time = g_get_monotonic_time ();
268 span = end_time - start_time;
270 if G_UNLIKELY (span < 0)
272 else if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * (DWORD) INFINITE)
273 span_millis = INFINITE;
275 /* Round up so we don't time out too early */
276 span_millis = (span + 1000 - 1) / 1000;
278 /* We never want to wait infinitely */
279 if (span_millis >= INFINITE)
280 span_millis = INFINITE - 1;
282 signalled = SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, span_millis, 0);
286 /* In case we didn't wait long enough after a timeout, wait again for the
288 start_time = g_get_monotonic_time ();
290 while (start_time < end_time);
297 typedef struct _GPrivateDestructor GPrivateDestructor;
299 struct _GPrivateDestructor
302 GDestroyNotify notify;
303 GPrivateDestructor *next;
306 static GPrivateDestructor *g_private_destructors; /* (atomic) prepend-only */
307 static CRITICAL_SECTION g_private_lock;
310 g_private_get_impl (GPrivate *key)
312 DWORD impl = (DWORD) GPOINTER_TO_UINT(key->p);
314 if G_UNLIKELY (impl == 0)
316 EnterCriticalSection (&g_private_lock);
317 impl = (UINT_PTR) key->p;
320 GPrivateDestructor *destructor;
324 if G_UNLIKELY (impl == 0)
326 /* Ignore TLS index 0 temporarily (as 0 is the indicator that we
327 * haven't allocated TLS yet) and alloc again;
328 * See https://gitlab.gnome.org/GNOME/glib/-/issues/2058 */
329 DWORD impl2 = TlsAlloc ();
334 if (impl == TLS_OUT_OF_INDEXES || impl == 0)
335 g_thread_abort (0, "TlsAlloc");
337 if (key->notify != NULL)
339 destructor = malloc (sizeof (GPrivateDestructor));
340 if G_UNLIKELY (destructor == NULL)
341 g_thread_abort (errno, "malloc");
342 destructor->index = impl;
343 destructor->notify = key->notify;
344 destructor->next = g_atomic_pointer_get (&g_private_destructors);
346 /* We need to do an atomic store due to the unlocked
347 * access to the destructor list from the thread exit
350 * It can double as a sanity check...
352 if (!g_atomic_pointer_compare_and_exchange (&g_private_destructors,
355 g_thread_abort (0, "g_private_get_impl(1)");
358 /* Ditto, due to the unlocked access on the fast path */
359 if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, GUINT_TO_POINTER (impl)))
360 g_thread_abort (0, "g_private_get_impl(2)");
362 LeaveCriticalSection (&g_private_lock);
369 g_private_get (GPrivate *key)
371 return TlsGetValue (g_private_get_impl (key));
375 g_private_set (GPrivate *key,
378 TlsSetValue (g_private_get_impl (key), value);
382 g_private_replace (GPrivate *key,
385 DWORD impl = g_private_get_impl (key);
388 old = TlsGetValue (impl);
389 TlsSetValue (impl, value);
390 if (old && key->notify)
396 #define win32_check_for_error(what) G_STMT_START{ \
398 g_error ("file %s: line %d (%s): error %s during %s", \
399 __FILE__, __LINE__, G_STRFUNC, \
400 g_win32_error_message (GetLastError ()), #what); \
403 #define G_MUTEX_SIZE (sizeof (gpointer))
405 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
416 g_system_thread_free (GRealThread *thread)
418 GThreadWin32 *wt = (GThreadWin32 *) thread;
420 win32_check_for_error (CloseHandle (wt->handle));
421 g_slice_free (GThreadWin32, wt);
425 g_system_thread_exit (void)
430 static guint __stdcall
431 g_thread_win32_proxy (gpointer data)
433 GThreadWin32 *self = data;
437 g_system_thread_exit ();
439 g_assert_not_reached ();
445 g_system_thread_new (GThreadFunc proxy,
452 GThreadWin32 *thread;
453 GRealThread *base_thread;
455 const gchar *message = NULL;
458 thread = g_slice_new0 (GThreadWin32);
459 thread->proxy = proxy;
460 thread->handle = (HANDLE) NULL;
461 base_thread = (GRealThread*)thread;
462 base_thread->ref_count = 2;
463 base_thread->ours = TRUE;
464 base_thread->thread.joinable = TRUE;
465 base_thread->thread.func = func;
466 base_thread->thread.data = data;
467 base_thread->name = g_strdup (name);
469 thread->handle = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_win32_proxy, thread,
470 CREATE_SUSPENDED, &ignore);
472 if (thread->handle == NULL)
474 message = "Error creating thread";
478 /* For thread priority inheritance we need to manually set the thread
479 * priority of the new thread to the priority of the current thread. We
480 * also have to start the thread suspended and resume it after actually
481 * setting the priority here.
483 * On Windows, by default all new threads are created with NORMAL thread
487 HANDLE current_thread = GetCurrentThread ();
488 thread_prio = GetThreadPriority (current_thread);
491 if (thread_prio == THREAD_PRIORITY_ERROR_RETURN)
493 message = "Error getting current thread priority";
497 if (SetThreadPriority (thread->handle, thread_prio) == 0)
499 message = "Error setting new thread priority";
503 if (ResumeThread (thread->handle) == (DWORD) -1)
505 message = "Error resuming new thread";
509 return (GRealThread *) thread;
513 gchar *win_error = g_win32_error_message (GetLastError ());
514 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
515 "%s: %s", message, win_error);
518 CloseHandle (thread->handle);
519 g_slice_free (GThreadWin32, thread);
525 g_thread_yield (void)
531 g_system_thread_wait (GRealThread *thread)
533 GThreadWin32 *wt = (GThreadWin32 *) thread;
535 win32_check_for_error (WAIT_FAILED != WaitForSingleObject (wt->handle, INFINITE));
538 #define EXCEPTION_SET_THREAD_NAME ((DWORD) 0x406D1388)
541 static void *SetThreadName_VEH_handle = NULL;
543 static LONG __stdcall
544 SetThreadName_VEH (PEXCEPTION_POINTERS ExceptionInfo)
546 if (ExceptionInfo->ExceptionRecord != NULL &&
547 ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SET_THREAD_NAME)
548 return EXCEPTION_CONTINUE_EXECUTION;
550 return EXCEPTION_CONTINUE_SEARCH;
554 typedef struct _THREADNAME_INFO
556 DWORD dwType; /* must be 0x1000 */
557 LPCSTR szName; /* pointer to name (in user addr space) */
558 DWORD dwThreadID; /* thread ID (-1=caller thread) */
559 DWORD dwFlags; /* reserved for future use, must be zero */
563 SetThreadName (DWORD dwThreadID,
566 THREADNAME_INFO info;
569 info.dwType = 0x1000;
570 info.szName = szThreadName;
571 info.dwThreadID = dwThreadID;
574 infosize = sizeof (info) / sizeof (ULONG_PTR);
579 RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize,
580 (const ULONG_PTR *) &info);
582 __except (GetExceptionCode () == EXCEPTION_SET_THREAD_NAME ?
583 EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
587 if ((!IsDebuggerPresent ()) || (SetThreadName_VEH_handle == NULL))
590 RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize, (const ULONG_PTR *) &info);
594 typedef HRESULT (WINAPI *pSetThreadDescription) (HANDLE hThread,
595 PCWSTR lpThreadDescription);
596 static pSetThreadDescription SetThreadDescriptionFunc = NULL;
597 static HMODULE kernel32_module = NULL;
600 g_thread_win32_load_library (void)
602 /* FIXME: Add support for UWP app */
603 #if !defined(G_WINAPI_ONLY_APP)
604 static gsize _init_once = 0;
605 if (g_once_init_enter (&_init_once))
607 kernel32_module = LoadLibraryW (L"kernel32.dll");
610 SetThreadDescriptionFunc =
611 (pSetThreadDescription) GetProcAddress (kernel32_module,
612 "SetThreadDescription");
613 if (!SetThreadDescriptionFunc)
614 FreeLibrary (kernel32_module);
616 g_once_init_leave (&_init_once, 1);
620 return !!SetThreadDescriptionFunc;
624 g_thread_win32_set_thread_desc (const gchar *name)
629 if (!g_thread_win32_load_library () || !name)
632 namew = g_utf8_to_utf16 (name, -1, NULL, NULL, NULL);
636 hr = SetThreadDescriptionFunc (GetCurrentThread (), namew);
639 return SUCCEEDED (hr);
643 g_system_thread_set_name (const gchar *name)
645 /* Prefer SetThreadDescription over exception based way if available,
646 * since thread description set by SetThreadDescription will be preserved
648 if (!g_thread_win32_set_thread_desc (name))
649 SetThreadName ((DWORD) -1, name);
655 g_thread_win32_init (void)
657 InitializeCriticalSection (&g_private_lock);
660 /* Set the handler as last to not interfere with ASAN runtimes.
661 * Many ASAN implementations (currently all three of GCC, CLANG
662 * and MSVC) install a Vectored Exception Handler that must be
663 * first in the sequence to work well
665 SetThreadName_VEH_handle = AddVectoredExceptionHandler (0, &SetThreadName_VEH);
666 if (SetThreadName_VEH_handle == NULL)
667 g_critical ("%s failed with error code %u",
668 "AddVectoredExceptionHandler", (unsigned int) GetLastError ());
673 g_thread_win32_thread_detach (void)
675 gboolean dtors_called;
679 GPrivateDestructor *dtor;
681 /* We go by the POSIX book on this one.
683 * If we call a destructor then there is a chance that some new
684 * TLS variables got set by code called in that destructor.
686 * Loop until nothing is left.
688 dtors_called = FALSE;
690 for (dtor = g_atomic_pointer_get (&g_private_destructors); dtor; dtor = dtor->next)
694 value = TlsGetValue (dtor->index);
695 if (value != NULL && dtor->notify != NULL)
697 /* POSIX says to clear this before the call */
698 TlsSetValue (dtor->index, NULL);
699 dtor->notify (value);
704 while (dtors_called);
708 g_thread_win32_process_detach (void)
711 if (SetThreadName_VEH_handle != NULL)
713 RemoveVectoredExceptionHandler (SetThreadName_VEH_handle);
714 SetThreadName_VEH_handle = NULL;
719 /* vim:set foldmethod=marker: */