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 cond = malloc (sizeof (GCond));
263 if G_UNLIKELY (cond == NULL)
264 g_thread_abort (errno, "malloc");
271 g_cond_free (GCond *cond)
280 #include "gthreadprivate.h"
282 #define win32_check_for_error(what) G_STMT_START{ \
284 g_error ("file %s: line %d (%s): error %s during %s", \
285 __FILE__, __LINE__, G_STRFUNC, \
286 g_win32_error_message (GetLastError ()), #what); \
289 #define G_MUTEX_SIZE (sizeof (gpointer))
291 static DWORD g_thread_self_tls;
292 static DWORD g_private_tls;
293 static CRITICAL_SECTION g_thread_global_spinlock;
295 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
297 /* As noted in the docs, GPrivate is a limited resource, here we take
298 * a rather low maximum to save memory, use GStaticPrivate instead. */
299 #define G_PRIVATE_MAX 100
301 static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
303 static guint g_private_next = 0;
305 typedef struct _GThreadData GThreadData;
315 g_private_new_win32_impl (GDestroyNotify destructor)
318 EnterCriticalSection (&g_thread_global_spinlock);
319 if (g_private_next >= G_PRIVATE_MAX)
323 "Too many GPrivate allocated. Their number is limited to %d.",
325 MessageBox (NULL, buf, NULL, MB_ICONERROR|MB_SETFOREGROUND);
326 if (IsDebuggerPresent ())
330 g_private_destructors[g_private_next] = destructor;
331 result = GUINT_TO_POINTER (g_private_next);
333 LeaveCriticalSection (&g_thread_global_spinlock);
338 /* NOTE: the functions g_private_get and g_private_set may not use
339 functions from gmem.c and gmessages.c */
342 g_private_set_win32_impl (GPrivate * private_key, gpointer value)
344 gpointer* array = TlsGetValue (g_private_tls);
345 guint index = GPOINTER_TO_UINT (private_key);
347 if (index >= G_PRIVATE_MAX)
352 array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
353 TlsSetValue (g_private_tls, array);
356 array[index] = value;
360 g_private_get_win32_impl (GPrivate * private_key)
362 gpointer* array = TlsGetValue (g_private_tls);
363 guint index = GPOINTER_TO_UINT (private_key);
365 if (index >= G_PRIVATE_MAX || !array)
374 g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
376 GThreadData *target = *(GThreadData **)thread;
381 case G_THREAD_PRIORITY_LOW:
382 native_prio = THREAD_PRIORITY_BELOW_NORMAL;
385 case G_THREAD_PRIORITY_NORMAL:
386 native_prio = THREAD_PRIORITY_NORMAL;
389 case G_THREAD_PRIORITY_HIGH:
390 native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
393 case G_THREAD_PRIORITY_URGENT:
394 native_prio = THREAD_PRIORITY_HIGHEST;
398 g_return_if_reached ();
401 win32_check_for_error (SetThreadPriority (target->thread, native_prio));
405 g_thread_self_win32_impl (gpointer thread)
407 GThreadData *self = TlsGetValue (g_thread_self_tls);
411 /* This should only happen for the main thread! */
412 HANDLE handle = GetCurrentThread ();
413 HANDLE process = GetCurrentProcess ();
414 self = g_new (GThreadData, 1);
415 win32_check_for_error (DuplicateHandle (process, handle, process,
416 &self->thread, 0, FALSE,
417 DUPLICATE_SAME_ACCESS));
418 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
421 self->joinable = FALSE;
424 *(GThreadData **)thread = self;
428 g_thread_exit_win32_impl (void)
430 GThreadData *self = TlsGetValue (g_thread_self_tls);
431 guint i, private_max;
432 gpointer *array = TlsGetValue (g_private_tls);
434 EnterCriticalSection (&g_thread_global_spinlock);
435 private_max = g_private_next;
436 LeaveCriticalSection (&g_thread_global_spinlock);
440 gboolean some_data_non_null;
443 some_data_non_null = FALSE;
444 for (i = 0; i < private_max; i++)
446 GDestroyNotify destructor = g_private_destructors[i];
447 GDestroyNotify data = array[i];
450 some_data_non_null = TRUE;
454 if (destructor && data)
457 } while (some_data_non_null);
461 win32_check_for_error (TlsSetValue (g_private_tls, NULL));
468 win32_check_for_error (CloseHandle (self->thread));
471 win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
474 if (g_thread_impl_vtable.CallThisOnThreadExit)
475 g_thread_impl_vtable.CallThisOnThreadExit ();
480 static guint __stdcall
481 g_thread_proxy (gpointer data)
483 GThreadData *self = (GThreadData*) data;
485 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
487 self->func (self->data);
489 g_thread_exit_win32_impl ();
491 g_assert_not_reached ();
497 g_thread_create_win32_impl (GThreadFunc func,
502 GThreadPriority priority,
509 g_return_if_fail (func);
510 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
511 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
513 retval = g_new(GThreadData, 1);
517 retval->joinable = joinable;
519 retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
522 if (retval->thread == NULL)
524 gchar *win_error = g_win32_error_message (GetLastError ());
525 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
526 "Error creating thread: %s", win_error);
532 *(GThreadData **)thread = retval;
534 g_thread_set_priority_win32_impl (thread, priority);
538 g_thread_yield_win32_impl (void)
544 g_thread_join_win32_impl (gpointer thread)
546 GThreadData *target = *(GThreadData **)thread;
548 g_return_if_fail (target->joinable);
550 win32_check_for_error (WAIT_FAILED !=
551 WaitForSingleObject (target->thread, INFINITE));
553 win32_check_for_error (CloseHandle (target->thread));
557 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
559 static DWORD g_thread_xp_waiter_tls;
560 static CRITICAL_SECTION g_thread_xp_lock;
562 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
563 typedef struct _GThreadXpWaiter GThreadXpWaiter;
564 struct _GThreadXpWaiter
567 volatile GThreadXpWaiter *next;
570 static GThreadXpWaiter *
571 g_thread_xp_waiter_get (void)
573 GThreadXpWaiter *waiter;
575 waiter = TlsGetValue (g_thread_xp_waiter_tls);
577 if G_UNLIKELY (waiter == NULL)
579 waiter = malloc (sizeof (GThreadXpWaiter));
581 g_thread_abort (GetLastError (), "malloc");
582 waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
583 if (waiter->event == NULL)
584 g_thread_abort (GetLastError (), "CreateEvent");
586 TlsSetValue (g_thread_xp_waiter_tls, waiter);
593 g_thread_xp_CallThisOnThreadExit (void)
595 GThreadXpWaiter *waiter;
597 waiter = TlsGetValue (g_thread_xp_waiter_tls);
601 TlsSetValue (g_thread_xp_waiter_tls, NULL);
602 CloseHandle (waiter->event);
607 /* {{{2 SRWLock emulation */
610 CRITICAL_SECTION critical_section;
614 g_thread_xp_InitializeSRWLock (gpointer mutex)
616 *(GThreadSRWLock * volatile *) mutex = NULL;
620 g_thread_xp_DeleteSRWLock (gpointer mutex)
622 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
626 DeleteCriticalSection (&lock->critical_section);
631 static GThreadSRWLock *
632 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
634 GThreadSRWLock *result;
636 /* It looks like we're missing some barriers here, but this code only
637 * ever runs on Windows XP, which in turn only ever runs on hardware
638 * with a relatively rigid memory model. The 'volatile' will take
639 * care of the compiler.
643 if G_UNLIKELY (result == NULL)
645 EnterCriticalSection (&g_thread_xp_lock);
647 result = malloc (sizeof (GThreadSRWLock));
650 g_thread_abort (errno, "malloc");
652 InitializeCriticalSection (&result->critical_section);
655 LeaveCriticalSection (&g_thread_xp_lock);
662 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
664 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
666 EnterCriticalSection (&lock->critical_section);
670 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
672 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
674 return TryEnterCriticalSection (&lock->critical_section);
678 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
680 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
682 /* We need this until we fix some weird parts of GLib that try to
683 * unlock freshly-allocated mutexes.
686 LeaveCriticalSection (&lock->critical_section);
689 /* {{{2 CONDITION_VARIABLE emulation */
692 volatile GThreadXpWaiter *first;
693 volatile GThreadXpWaiter **last_ptr;
694 } GThreadXpCONDITION_VARIABLE;
697 g_thread_xp_InitializeConditionVariable (gpointer cond)
699 *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
703 g_thread_xp_DeleteConditionVariable (gpointer cond)
705 GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
711 static GThreadXpCONDITION_VARIABLE *
712 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
714 GThreadXpCONDITION_VARIABLE *result;
716 /* It looks like we're missing some barriers here, but this code only
717 * ever runs on Windows XP, which in turn only ever runs on hardware
718 * with a relatively rigid memory model. The 'volatile' will take
719 * care of the compiler.
723 if G_UNLIKELY (result == NULL)
725 result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
728 g_thread_abort (errno, "malloc");
730 result->first = NULL;
731 result->last_ptr = &result->first;
733 if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
744 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
749 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
750 GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
755 EnterCriticalSection (&g_thread_xp_lock);
756 *cv->last_ptr = waiter;
757 cv->last_ptr = &waiter->next;
758 LeaveCriticalSection (&g_thread_xp_lock);
760 g_mutex_unlock (mutex);
761 status = WaitForSingleObject (waiter->event, timeout);
763 if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
764 g_thread_abort (GetLastError (), "WaitForSingleObject");
766 g_mutex_lock (mutex);
768 return status == WAIT_OBJECT_0;
772 g_thread_xp_WakeConditionVariable (gpointer cond)
774 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
775 volatile GThreadXpWaiter *waiter;
777 EnterCriticalSection (&g_thread_xp_lock);
781 cv->first = waiter->next;
782 if (cv->first == NULL)
783 cv->last_ptr = &cv->first;
785 LeaveCriticalSection (&g_thread_xp_lock);
788 SetEvent (waiter->event);
792 g_thread_xp_WakeAllConditionVariable (gpointer cond)
794 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
795 volatile GThreadXpWaiter *waiter;
797 EnterCriticalSection (&g_thread_xp_lock);
800 cv->last_ptr = &cv->first;
801 LeaveCriticalSection (&g_thread_xp_lock);
803 while (waiter != NULL)
805 volatile GThreadXpWaiter *next;
808 SetEvent (waiter->event);
815 g_thread_xp_init (void)
817 static const GThreadImplVtable g_thread_xp_impl_vtable = {
818 g_thread_xp_CallThisOnThreadExit,
819 g_thread_xp_InitializeSRWLock,
820 g_thread_xp_DeleteSRWLock,
821 g_thread_xp_AcquireSRWLockExclusive,
822 g_thread_xp_TryAcquireSRWLockExclusive,
823 g_thread_xp_ReleaseSRWLockExclusive,
824 g_thread_xp_InitializeConditionVariable,
825 g_thread_xp_DeleteConditionVariable,
826 g_thread_xp_SleepConditionVariableSRW,
827 g_thread_xp_WakeAllConditionVariable,
828 g_thread_xp_WakeConditionVariable
831 InitializeCriticalSection (&g_thread_xp_lock);
832 g_thread_xp_waiter_tls = TlsAlloc ();
834 g_thread_impl_vtable = g_thread_xp_impl_vtable;
839 GThreadFunctions g_thread_functions_for_glib_use =
841 g_mutex_new, /* mutex */
846 g_cond_new, /* condition */
852 g_private_new_win32_impl, /* private thread data */
853 g_private_get_win32_impl,
854 g_private_set_win32_impl,
855 g_thread_create_win32_impl, /* thread */
856 g_thread_yield_win32_impl,
857 g_thread_join_win32_impl,
858 g_thread_exit_win32_impl,
859 g_thread_set_priority_win32_impl,
860 g_thread_self_win32_impl,
861 NULL /* no equal function necessary */
865 _g_thread_impl_init (void)
867 static gboolean beenhere = FALSE;
874 printf ("thread init\n");
875 win32_check_for_error (TLS_OUT_OF_INDEXES !=
876 (g_thread_self_tls = TlsAlloc ()));
877 win32_check_for_error (TLS_OUT_OF_INDEXES !=
878 (g_private_tls = TlsAlloc ()));
879 InitializeCriticalSection (&g_thread_global_spinlock);
883 g_thread_lookup_native_funcs (void)
885 GThreadImplVtable native_vtable = { 0, };
888 kernel32 = GetModuleHandle ("KERNEL32.DLL");
890 if (kernel32 == NULL)
893 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
894 GET_FUNC(InitializeSRWLock);
895 GET_FUNC(AcquireSRWLockExclusive);
896 GET_FUNC(TryAcquireSRWLockExclusive);
897 GET_FUNC(ReleaseSRWLockExclusive);
899 GET_FUNC(InitializeConditionVariable);
900 GET_FUNC(SleepConditionVariableSRW);
901 GET_FUNC(WakeAllConditionVariable);
902 GET_FUNC(WakeConditionVariable);
905 g_thread_impl_vtable = native_vtable;
911 g_thread_DllMain (void)
913 /* XXX This is broken right now for some unknown reason...
915 if (g_thread_lookup_native_funcs ())
916 fprintf (stderr, "(debug) GThread using native mode\n");
920 fprintf (stderr, "(debug) GThread using Windows XP mode\n");
925 /* vim:set foldmethod=marker: */