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 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
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.
47 #define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
55 g_thread_abort (gint status,
56 const gchar *function)
58 fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s. Aborting.\n",
59 strerror (status), function);
63 /* Starting with Vista and Windows 2008, we have access to the
64 * CONDITION_VARIABLE and SRWLock primatives on Windows, which are
65 * pretty reasonable approximations of the primatives specified in
66 * POSIX 2001 (pthread_cond_t and pthread_mutex_t respectively).
68 * Both of these types are structs containing a single pointer. That
69 * pointer is used as an atomic bitfield to support user-space mutexes
70 * that only get the kernel involved in cases of contention (similar
71 * to how futex()-based mutexes work on Linux). The biggest advantage
72 * of these new types is that they can be statically initialised to
73 * zero. This allows us to use them directly and still support:
75 * GMutex mutex = G_MUTEX_INIT;
79 * GCond cond = G_COND_INIT;
81 * Unfortunately, Windows XP lacks these facilities and GLib still
82 * needs to support Windows XP. Our approach here is as follows:
84 * - avoid depending on structure declarations at compile-time by
85 * declaring our own GMutex and GCond strutures to be
86 * ABI-compatible with SRWLock and CONDITION_VARIABLE and using
89 * - avoid a hard dependency on the symbols used to manipulate these
90 * structures by doing a dynamic lookup of those symbols at
93 * - if the symbols are not available, emulate them using other
96 * Using this approach also allows us to easily build a GLib that lacks
97 * support for Windows XP or to remove this code entirely when XP is no
98 * longer supported (end of line is currently April 8, 2014).
102 void (* CallThisOnThreadExit) (void); /* fake */
104 void (* InitializeSRWLock) (gpointer lock);
105 void (* DeleteSRWLock) (gpointer lock); /* fake */
106 void (* AcquireSRWLockExclusive) (gpointer lock);
107 BOOLEAN (* TryAcquireSRWLockExclusive) (gpointer lock);
108 void (* ReleaseSRWLockExclusive) (gpointer lock);
110 void (* InitializeConditionVariable) (gpointer cond);
111 void (* DeleteConditionVariable) (gpointer cond); /* fake */
112 BOOL (* SleepConditionVariableSRW) (gpointer cond,
116 void (* WakeAllConditionVariable) (gpointer cond);
117 void (* WakeConditionVariable) (gpointer cond);
120 static GThreadImplVtable g_thread_impl_vtable;
124 g_mutex_init (GMutex *mutex)
126 g_thread_impl_vtable.InitializeSRWLock (mutex);
130 g_mutex_clear (GMutex *mutex)
132 if (g_thread_impl_vtable.DeleteSRWLock != NULL)
133 g_thread_impl_vtable.DeleteSRWLock (mutex);
137 g_mutex_lock (GMutex *mutex)
139 /* temporary until we fix libglib */
143 g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
147 g_mutex_trylock (GMutex *mutex)
149 /* temporary until we fix libglib */
153 return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
157 g_mutex_unlock (GMutex *mutex)
159 /* temporary until we fix libglib */
163 g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
168 g_cond_init (GCond *cond)
170 g_thread_impl_vtable.InitializeConditionVariable (cond);
174 g_cond_clear (GCond *cond)
176 if (g_thread_impl_vtable.DeleteConditionVariable)
177 g_thread_impl_vtable.DeleteConditionVariable (cond);
181 g_cond_signal (GCond *cond)
183 /* temporary until we fix libglib */
187 g_thread_impl_vtable.WakeConditionVariable (cond);
191 g_cond_broadcast (GCond *cond)
193 /* temporary until we fix libglib */
197 g_thread_impl_vtable.WakeAllConditionVariable (cond);
201 g_cond_wait (GCond *cond,
202 GMutex *entered_mutex)
204 g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
208 g_cond_timedwait (GCond *cond,
209 GMutex *entered_mutex,
216 GetSystemTimeAsFileTime (&ft);
217 memmove (&now, &ft, sizeof (FILETIME));
219 now -= G_GINT64_CONSTANT (116444736000000000);
222 span = abs_time - now;
224 if G_UNLIKELY (span < 0)
227 if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
230 return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
234 g_cond_timed_wait (GCond *cond,
235 GMutex *entered_mutex,
242 micros = abs_time->tv_sec;
244 micros += abs_time->tv_usec;
246 return g_cond_timedwait (cond, entered_mutex, micros);
250 g_cond_wait (cond, entered_mutex);
255 /* {{{1 new/free API */
261 /* malloc() is temporary until all libglib users are ported away */
262 mutex = malloc (sizeof (GMutex));
263 if G_UNLIKELY (mutex == NULL)
264 g_thread_abort (errno, "malloc");
265 g_mutex_init (mutex);
271 g_mutex_free (GMutex *mutex)
273 g_mutex_clear (mutex);
282 /* malloc() is temporary until all libglib users are ported away */
283 cond = malloc (sizeof (GCond));
284 if G_UNLIKELY (cond == NULL)
285 g_thread_abort (errno, "malloc");
292 g_cond_free (GCond *cond)
301 #include "gthreadprivate.h"
303 #define win32_check_for_error(what) G_STMT_START{ \
305 g_error ("file %s: line %d (%s): error %s during %s", \
306 __FILE__, __LINE__, G_STRFUNC, \
307 g_win32_error_message (GetLastError ()), #what); \
310 #define G_MUTEX_SIZE (sizeof (gpointer))
312 static DWORD g_thread_self_tls;
313 static DWORD g_private_tls;
314 static CRITICAL_SECTION g_thread_global_spinlock;
316 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
318 /* As noted in the docs, GPrivate is a limited resource, here we take
319 * a rather low maximum to save memory, use GStaticPrivate instead. */
320 #define G_PRIVATE_MAX 100
322 static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
324 static guint g_private_next = 0;
326 typedef struct _GThreadData GThreadData;
336 g_private_new_win32_impl (GDestroyNotify destructor)
339 EnterCriticalSection (&g_thread_global_spinlock);
340 if (g_private_next >= G_PRIVATE_MAX)
344 "Too many GPrivate allocated. Their number is limited to %d.",
346 MessageBox (NULL, buf, NULL, MB_ICONERROR|MB_SETFOREGROUND);
347 if (IsDebuggerPresent ())
351 g_private_destructors[g_private_next] = destructor;
352 result = GUINT_TO_POINTER (g_private_next);
354 LeaveCriticalSection (&g_thread_global_spinlock);
359 /* NOTE: the functions g_private_get and g_private_set may not use
360 functions from gmem.c and gmessages.c */
363 g_private_set_win32_impl (GPrivate * private_key, gpointer value)
365 gpointer* array = TlsGetValue (g_private_tls);
366 guint index = GPOINTER_TO_UINT (private_key);
368 if (index >= G_PRIVATE_MAX)
373 array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
374 TlsSetValue (g_private_tls, array);
377 array[index] = value;
381 g_private_get_win32_impl (GPrivate * private_key)
383 gpointer* array = TlsGetValue (g_private_tls);
384 guint index = GPOINTER_TO_UINT (private_key);
386 if (index >= G_PRIVATE_MAX || !array)
395 g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
397 GThreadData *target = *(GThreadData **)thread;
402 case G_THREAD_PRIORITY_LOW:
403 native_prio = THREAD_PRIORITY_BELOW_NORMAL;
406 case G_THREAD_PRIORITY_NORMAL:
407 native_prio = THREAD_PRIORITY_NORMAL;
410 case G_THREAD_PRIORITY_HIGH:
411 native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
414 case G_THREAD_PRIORITY_URGENT:
415 native_prio = THREAD_PRIORITY_HIGHEST;
419 g_return_if_reached ();
422 win32_check_for_error (SetThreadPriority (target->thread, native_prio));
426 g_thread_self_win32_impl (gpointer thread)
428 GThreadData *self = TlsGetValue (g_thread_self_tls);
432 /* This should only happen for the main thread! */
433 HANDLE handle = GetCurrentThread ();
434 HANDLE process = GetCurrentProcess ();
435 self = g_new (GThreadData, 1);
436 win32_check_for_error (DuplicateHandle (process, handle, process,
437 &self->thread, 0, FALSE,
438 DUPLICATE_SAME_ACCESS));
439 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
442 self->joinable = FALSE;
445 *(GThreadData **)thread = self;
449 g_thread_exit_win32_impl (void)
451 GThreadData *self = TlsGetValue (g_thread_self_tls);
452 guint i, private_max;
453 gpointer *array = TlsGetValue (g_private_tls);
455 EnterCriticalSection (&g_thread_global_spinlock);
456 private_max = g_private_next;
457 LeaveCriticalSection (&g_thread_global_spinlock);
461 gboolean some_data_non_null;
464 some_data_non_null = FALSE;
465 for (i = 0; i < private_max; i++)
467 GDestroyNotify destructor = g_private_destructors[i];
468 GDestroyNotify data = array[i];
471 some_data_non_null = TRUE;
475 if (destructor && data)
478 } while (some_data_non_null);
482 win32_check_for_error (TlsSetValue (g_private_tls, NULL));
489 win32_check_for_error (CloseHandle (self->thread));
492 win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
495 if (g_thread_impl_vtable.CallThisOnThreadExit)
496 g_thread_impl_vtable.CallThisOnThreadExit ();
501 static guint __stdcall
502 g_thread_proxy (gpointer data)
504 GThreadData *self = (GThreadData*) data;
506 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
508 self->func (self->data);
510 g_thread_exit_win32_impl ();
512 g_assert_not_reached ();
518 g_thread_create_win32_impl (GThreadFunc func,
523 GThreadPriority priority,
530 g_return_if_fail (func);
531 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
532 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
534 retval = g_new(GThreadData, 1);
538 retval->joinable = joinable;
540 retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
543 if (retval->thread == NULL)
545 gchar *win_error = g_win32_error_message (GetLastError ());
546 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
547 "Error creating thread: %s", win_error);
553 *(GThreadData **)thread = retval;
555 g_thread_set_priority_win32_impl (thread, priority);
559 g_thread_yield_win32_impl (void)
565 g_thread_join_win32_impl (gpointer thread)
567 GThreadData *target = *(GThreadData **)thread;
569 g_return_if_fail (target->joinable);
571 win32_check_for_error (WAIT_FAILED !=
572 WaitForSingleObject (target->thread, INFINITE));
574 win32_check_for_error (CloseHandle (target->thread));
578 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
580 static DWORD g_thread_xp_waiter_tls;
581 static CRITICAL_SECTION g_thread_xp_lock;
583 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
584 typedef struct _GThreadXpWaiter GThreadXpWaiter;
585 struct _GThreadXpWaiter
588 volatile GThreadXpWaiter *next;
591 static GThreadXpWaiter *
592 g_thread_xp_waiter_get (void)
594 GThreadXpWaiter *waiter;
596 waiter = TlsGetValue (g_thread_xp_waiter_tls);
598 if G_UNLIKELY (waiter == NULL)
600 waiter = malloc (sizeof (GThreadXpWaiter));
602 g_thread_abort (GetLastError (), "malloc");
603 waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
604 if (waiter->event == NULL)
605 g_thread_abort (GetLastError (), "CreateEvent");
607 TlsSetValue (g_thread_xp_waiter_tls, waiter);
614 g_thread_xp_CallThisOnThreadExit (void)
616 GThreadXpWaiter *waiter;
618 waiter = TlsGetValue (g_thread_xp_waiter_tls);
622 TlsSetValue (g_thread_xp_waiter_tls, NULL);
623 CloseHandle (waiter->event);
628 /* {{{2 SRWLock emulation */
631 CRITICAL_SECTION critical_section;
635 g_thread_xp_InitializeSRWLock (gpointer mutex)
637 *(GThreadSRWLock * volatile *) mutex = NULL;
641 g_thread_xp_DeleteSRWLock (gpointer mutex)
643 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
647 DeleteCriticalSection (&lock->critical_section);
652 static GThreadSRWLock *
653 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
655 GThreadSRWLock *result;
657 /* It looks like we're missing some barriers here, but this code only
658 * ever runs on Windows XP, which in turn only ever runs on hardware
659 * with a relatively rigid memory model. The 'volatile' will take
660 * care of the compiler.
664 if G_UNLIKELY (result == NULL)
666 EnterCriticalSection (&g_thread_xp_lock);
668 result = malloc (sizeof (GThreadSRWLock));
671 g_thread_abort (errno, "malloc");
673 InitializeCriticalSection (&result->critical_section);
676 LeaveCriticalSection (&g_thread_xp_lock);
683 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
685 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
687 EnterCriticalSection (&lock->critical_section);
691 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
693 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
695 return TryEnterCriticalSection (&lock->critical_section);
699 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
701 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
703 /* We need this until we fix some weird parts of GLib that try to
704 * unlock freshly-allocated mutexes.
707 LeaveCriticalSection (&lock->critical_section);
710 /* {{{2 CONDITION_VARIABLE emulation */
713 volatile GThreadXpWaiter *first;
714 volatile GThreadXpWaiter **last_ptr;
715 } GThreadXpCONDITION_VARIABLE;
718 g_thread_xp_InitializeConditionVariable (gpointer cond)
720 *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
724 g_thread_xp_DeleteConditionVariable (gpointer cond)
726 GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
732 static GThreadXpCONDITION_VARIABLE *
733 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
735 GThreadXpCONDITION_VARIABLE *result;
737 /* It looks like we're missing some barriers here, but this code only
738 * ever runs on Windows XP, which in turn only ever runs on hardware
739 * with a relatively rigid memory model. The 'volatile' will take
740 * care of the compiler.
744 if G_UNLIKELY (result == NULL)
746 result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
749 g_thread_abort (errno, "malloc");
751 result->first = NULL;
752 result->last_ptr = &result->first;
754 if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
765 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
770 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
771 GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
776 EnterCriticalSection (&g_thread_xp_lock);
777 *cv->last_ptr = waiter;
778 cv->last_ptr = &waiter->next;
779 LeaveCriticalSection (&g_thread_xp_lock);
781 g_mutex_unlock (mutex);
782 status = WaitForSingleObject (waiter->event, timeout);
784 if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
785 g_thread_abort (GetLastError (), "WaitForSingleObject");
787 g_mutex_lock (mutex);
789 return status == WAIT_OBJECT_0;
793 g_thread_xp_WakeConditionVariable (gpointer cond)
795 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
796 volatile GThreadXpWaiter *waiter;
798 EnterCriticalSection (&g_thread_xp_lock);
802 cv->first = waiter->next;
803 if (cv->first == NULL)
804 cv->last_ptr = &cv->first;
806 LeaveCriticalSection (&g_thread_xp_lock);
809 SetEvent (waiter->event);
813 g_thread_xp_WakeAllConditionVariable (gpointer cond)
815 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
816 volatile GThreadXpWaiter *waiter;
818 EnterCriticalSection (&g_thread_xp_lock);
821 cv->last_ptr = &cv->first;
822 LeaveCriticalSection (&g_thread_xp_lock);
824 while (waiter != NULL)
826 volatile GThreadXpWaiter *next;
829 SetEvent (waiter->event);
836 g_thread_xp_init (void)
838 static const GThreadImplVtable g_thread_xp_impl_vtable = {
839 g_thread_xp_CallThisOnThreadExit,
840 g_thread_xp_InitializeSRWLock,
841 g_thread_xp_DeleteSRWLock,
842 g_thread_xp_AcquireSRWLockExclusive,
843 g_thread_xp_TryAcquireSRWLockExclusive,
844 g_thread_xp_ReleaseSRWLockExclusive,
845 g_thread_xp_InitializeConditionVariable,
846 g_thread_xp_DeleteConditionVariable,
847 g_thread_xp_SleepConditionVariableSRW,
848 g_thread_xp_WakeAllConditionVariable,
849 g_thread_xp_WakeConditionVariable
852 InitializeCriticalSection (&g_thread_xp_lock);
853 g_thread_xp_waiter_tls = TlsAlloc ();
855 g_thread_impl_vtable = g_thread_xp_impl_vtable;
860 GThreadFunctions g_thread_functions_for_glib_use =
862 g_mutex_new, /* mutex */
867 g_cond_new, /* condition */
873 g_private_new_win32_impl, /* private thread data */
874 g_private_get_win32_impl,
875 g_private_set_win32_impl,
876 g_thread_create_win32_impl, /* thread */
877 g_thread_yield_win32_impl,
878 g_thread_join_win32_impl,
879 g_thread_exit_win32_impl,
880 g_thread_set_priority_win32_impl,
881 g_thread_self_win32_impl,
882 NULL /* no equal function necessary */
886 _g_thread_impl_init (void)
888 static gboolean beenhere = FALSE;
895 printf ("thread init\n");
896 win32_check_for_error (TLS_OUT_OF_INDEXES !=
897 (g_thread_self_tls = TlsAlloc ()));
898 win32_check_for_error (TLS_OUT_OF_INDEXES !=
899 (g_private_tls = TlsAlloc ()));
900 InitializeCriticalSection (&g_thread_global_spinlock);
904 g_thread_lookup_native_funcs (void)
906 GThreadImplVtable native_vtable = { 0, };
909 kernel32 = GetModuleHandle ("KERNEL32.DLL");
911 if (kernel32 == NULL)
914 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
915 GET_FUNC(InitializeSRWLock);
916 GET_FUNC(AcquireSRWLockExclusive);
917 GET_FUNC(TryAcquireSRWLockExclusive);
918 GET_FUNC(ReleaseSRWLockExclusive);
920 GET_FUNC(InitializeConditionVariable);
921 GET_FUNC(SleepConditionVariableSRW);
922 GET_FUNC(WakeAllConditionVariable);
923 GET_FUNC(WakeConditionVariable);
926 g_thread_impl_vtable = native_vtable;
932 g_thread_DllMain (void)
934 /* XXX This is broken right now for some unknown reason...
936 if (g_thread_lookup_native_funcs ())
937 fprintf (stderr, "(debug) GThread using native mode\n");
941 fprintf (stderr, "(debug) GThread using Windows XP mode\n");
946 /* vim:set foldmethod=marker: */