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, 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)
427 /* In static compilation, DllMain doesn't exist and so DLL_THREAD_DETACH
428 * case is never called and thread destroy notifications are not triggered.
429 * To ensure that notifications are correctly triggered in static
430 * compilation mode, we call directly the "detach" function here right
431 * before terminating the thread.
432 * As all win32 threads initialized through the glib API are run through
433 * the same proxy function g_thread_win32_proxy() which calls systematically
434 * g_system_thread_exit() when finishing, we obtain the same behavior as
435 * with dynamic compilation.
437 * WARNING: unfortunately this mechanism cannot work with threads created
438 * directly from the Windows API using CreateThread() or _beginthread/ex().
439 * It only works with threads created by using the glib API with
440 * g_system_thread_new(). If users need absolutely to use a thread NOT
441 * created with glib API under Windows and in static compilation mode, they
442 * should not use glib functions within their thread or they may encounter
443 * memory leaks when the thread finishes.
445 #ifdef GLIB_STATIC_COMPILATION
446 g_thread_win32_thread_detach ();
452 static guint __stdcall
453 g_thread_win32_proxy (gpointer data)
455 GThreadWin32 *self = data;
459 g_system_thread_exit ();
461 g_assert_not_reached ();
467 g_system_thread_get_scheduler_settings (GThreadSchedulerSettings *scheduler_settings)
469 HANDLE current_thread = GetCurrentThread ();
470 scheduler_settings->thread_prio = GetThreadPriority (current_thread);
476 g_system_thread_new (GThreadFunc proxy,
478 const GThreadSchedulerSettings *scheduler_settings,
484 GThreadWin32 *thread;
485 GRealThread *base_thread;
487 const gchar *message = NULL;
490 thread = g_slice_new0 (GThreadWin32);
491 thread->proxy = proxy;
492 thread->handle = (HANDLE) NULL;
493 base_thread = (GRealThread*)thread;
494 base_thread->ref_count = 2;
495 base_thread->ours = TRUE;
496 base_thread->thread.joinable = TRUE;
497 base_thread->thread.func = func;
498 base_thread->thread.data = data;
499 base_thread->name = g_strdup (name);
501 thread->handle = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_win32_proxy, thread,
502 CREATE_SUSPENDED, &ignore);
504 if (thread->handle == NULL)
506 message = "Error creating thread";
510 /* For thread priority inheritance we need to manually set the thread
511 * priority of the new thread to the priority of the current thread. We
512 * also have to start the thread suspended and resume it after actually
513 * setting the priority here.
515 * On Windows, by default all new threads are created with NORMAL thread
519 if (scheduler_settings)
521 thread_prio = scheduler_settings->thread_prio;
525 HANDLE current_thread = GetCurrentThread ();
526 thread_prio = GetThreadPriority (current_thread);
529 if (thread_prio == THREAD_PRIORITY_ERROR_RETURN)
531 message = "Error getting current thread priority";
535 if (SetThreadPriority (thread->handle, thread_prio) == 0)
537 message = "Error setting new thread priority";
541 if (ResumeThread (thread->handle) == (DWORD) -1)
543 message = "Error resuming new thread";
547 return (GRealThread *) thread;
551 gchar *win_error = g_win32_error_message (GetLastError ());
552 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
553 "%s: %s", message, win_error);
556 CloseHandle (thread->handle);
557 g_slice_free (GThreadWin32, thread);
563 g_thread_yield (void)
569 g_system_thread_wait (GRealThread *thread)
571 GThreadWin32 *wt = (GThreadWin32 *) thread;
573 win32_check_for_error (WAIT_FAILED != WaitForSingleObject (wt->handle, INFINITE));
576 #define EXCEPTION_SET_THREAD_NAME ((DWORD) 0x406D1388)
579 static void *SetThreadName_VEH_handle = NULL;
581 static LONG __stdcall
582 SetThreadName_VEH (PEXCEPTION_POINTERS ExceptionInfo)
584 if (ExceptionInfo->ExceptionRecord != NULL &&
585 ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SET_THREAD_NAME)
586 return EXCEPTION_CONTINUE_EXECUTION;
588 return EXCEPTION_CONTINUE_SEARCH;
592 typedef struct _THREADNAME_INFO
594 DWORD dwType; /* must be 0x1000 */
595 LPCSTR szName; /* pointer to name (in user addr space) */
596 DWORD dwThreadID; /* thread ID (-1=caller thread) */
597 DWORD dwFlags; /* reserved for future use, must be zero */
601 SetThreadName (DWORD dwThreadID,
604 THREADNAME_INFO info;
607 info.dwType = 0x1000;
608 info.szName = szThreadName;
609 info.dwThreadID = dwThreadID;
612 infosize = sizeof (info) / sizeof (DWORD);
617 RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize,
618 (const ULONG_PTR *) &info);
620 __except (EXCEPTION_EXECUTE_HANDLER)
624 /* Without a debugger we *must* have an exception handler,
625 * otherwise raising an exception will crash the process.
627 if ((!IsDebuggerPresent ()) && (SetThreadName_VEH_handle == NULL))
630 RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize, (const ULONG_PTR *) &info);
634 typedef HRESULT (WINAPI *pSetThreadDescription) (HANDLE hThread,
635 PCWSTR lpThreadDescription);
636 static pSetThreadDescription SetThreadDescriptionFunc = NULL;
637 static HMODULE kernel32_module = NULL;
640 g_thread_win32_load_library (void)
642 /* FIXME: Add support for UWP app */
643 #if !defined(G_WINAPI_ONLY_APP)
644 static gsize _init_once = 0;
645 if (g_once_init_enter (&_init_once))
647 kernel32_module = LoadLibraryW (L"kernel32.dll");
650 SetThreadDescriptionFunc =
651 (pSetThreadDescription) GetProcAddress (kernel32_module,
652 "SetThreadDescription");
653 if (!SetThreadDescriptionFunc)
654 FreeLibrary (kernel32_module);
656 g_once_init_leave (&_init_once, 1);
660 return !!SetThreadDescriptionFunc;
664 g_thread_win32_set_thread_desc (const gchar *name)
669 if (!g_thread_win32_load_library () || !name)
672 namew = g_utf8_to_utf16 (name, -1, NULL, NULL, NULL);
676 hr = SetThreadDescriptionFunc (GetCurrentThread (), namew);
679 return SUCCEEDED (hr);
683 g_system_thread_set_name (const gchar *name)
685 /* Prefer SetThreadDescription over exception based way if available,
686 * since thread description set by SetThreadDescription will be preserved
688 if (!g_thread_win32_set_thread_desc (name))
689 SetThreadName ((DWORD) -1, name);
695 g_thread_win32_init (void)
697 InitializeCriticalSection (&g_private_lock);
700 SetThreadName_VEH_handle = AddVectoredExceptionHandler (1, &SetThreadName_VEH);
701 if (SetThreadName_VEH_handle == NULL)
703 /* This is bad, but what can we do? */
709 g_thread_win32_thread_detach (void)
711 gboolean dtors_called;
715 GPrivateDestructor *dtor;
717 /* We go by the POSIX book on this one.
719 * If we call a destructor then there is a chance that some new
720 * TLS variables got set by code called in that destructor.
722 * Loop until nothing is left.
724 dtors_called = FALSE;
726 for (dtor = g_atomic_pointer_get (&g_private_destructors); dtor; dtor = dtor->next)
730 value = TlsGetValue (dtor->index);
731 if (value != NULL && dtor->notify != NULL)
733 /* POSIX says to clear this before the call */
734 TlsSetValue (dtor->index, NULL);
735 dtor->notify (value);
740 while (dtors_called);
744 g_thread_win32_process_detach (void)
747 if (SetThreadName_VEH_handle != NULL)
749 RemoveVectoredExceptionHandler (SetThreadName_VEH_handle);
750 SetThreadName_VEH_handle = NULL;
755 /* vim:set foldmethod=marker: */