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);
258 #include "gthreadprivate.h"
260 #define win32_check_for_error(what) G_STMT_START{ \
262 g_error ("file %s: line %d (%s): error %s during %s", \
263 __FILE__, __LINE__, G_STRFUNC, \
264 g_win32_error_message (GetLastError ()), #what); \
267 #define G_MUTEX_SIZE (sizeof (gpointer))
269 static DWORD g_thread_self_tls;
270 static DWORD g_private_tls;
271 static CRITICAL_SECTION g_thread_global_spinlock;
273 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
275 /* As noted in the docs, GPrivate is a limited resource, here we take
276 * a rather low maximum to save memory, use GStaticPrivate instead. */
277 #define G_PRIVATE_MAX 100
279 static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
281 static guint g_private_next = 0;
283 typedef struct _GThreadData GThreadData;
293 g_private_new_win32_impl (GDestroyNotify destructor)
296 EnterCriticalSection (&g_thread_global_spinlock);
297 if (g_private_next >= G_PRIVATE_MAX)
301 "Too many GPrivate allocated. Their number is limited to %d.",
303 MessageBox (NULL, buf, NULL, MB_ICONERROR|MB_SETFOREGROUND);
304 if (IsDebuggerPresent ())
308 g_private_destructors[g_private_next] = destructor;
309 result = GUINT_TO_POINTER (g_private_next);
311 LeaveCriticalSection (&g_thread_global_spinlock);
316 /* NOTE: the functions g_private_get and g_private_set may not use
317 functions from gmem.c and gmessages.c */
320 g_private_set_win32_impl (GPrivate * private_key, gpointer value)
322 gpointer* array = TlsGetValue (g_private_tls);
323 guint index = GPOINTER_TO_UINT (private_key);
325 if (index >= G_PRIVATE_MAX)
330 array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
331 TlsSetValue (g_private_tls, array);
334 array[index] = value;
338 g_private_get_win32_impl (GPrivate * private_key)
340 gpointer* array = TlsGetValue (g_private_tls);
341 guint index = GPOINTER_TO_UINT (private_key);
343 if (index >= G_PRIVATE_MAX || !array)
352 g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
354 GThreadData *target = *(GThreadData **)thread;
359 case G_THREAD_PRIORITY_LOW:
360 native_prio = THREAD_PRIORITY_BELOW_NORMAL;
363 case G_THREAD_PRIORITY_NORMAL:
364 native_prio = THREAD_PRIORITY_NORMAL;
367 case G_THREAD_PRIORITY_HIGH:
368 native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
371 case G_THREAD_PRIORITY_URGENT:
372 native_prio = THREAD_PRIORITY_HIGHEST;
376 g_return_if_reached ();
379 win32_check_for_error (SetThreadPriority (target->thread, native_prio));
383 g_thread_self_win32_impl (gpointer thread)
385 GThreadData *self = TlsGetValue (g_thread_self_tls);
389 /* This should only happen for the main thread! */
390 HANDLE handle = GetCurrentThread ();
391 HANDLE process = GetCurrentProcess ();
392 self = g_new (GThreadData, 1);
393 win32_check_for_error (DuplicateHandle (process, handle, process,
394 &self->thread, 0, FALSE,
395 DUPLICATE_SAME_ACCESS));
396 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
399 self->joinable = FALSE;
402 *(GThreadData **)thread = self;
406 g_thread_exit_win32_impl (void)
408 GThreadData *self = TlsGetValue (g_thread_self_tls);
409 guint i, private_max;
410 gpointer *array = TlsGetValue (g_private_tls);
412 EnterCriticalSection (&g_thread_global_spinlock);
413 private_max = g_private_next;
414 LeaveCriticalSection (&g_thread_global_spinlock);
418 gboolean some_data_non_null;
421 some_data_non_null = FALSE;
422 for (i = 0; i < private_max; i++)
424 GDestroyNotify destructor = g_private_destructors[i];
425 GDestroyNotify data = array[i];
428 some_data_non_null = TRUE;
432 if (destructor && data)
435 } while (some_data_non_null);
439 win32_check_for_error (TlsSetValue (g_private_tls, NULL));
446 win32_check_for_error (CloseHandle (self->thread));
449 win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
452 if (g_thread_impl_vtable.CallThisOnThreadExit)
453 g_thread_impl_vtable.CallThisOnThreadExit ();
458 static guint __stdcall
459 g_thread_proxy (gpointer data)
461 GThreadData *self = (GThreadData*) data;
463 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
465 self->func (self->data);
467 g_thread_exit_win32_impl ();
469 g_assert_not_reached ();
475 g_thread_create_win32_impl (GThreadFunc func,
480 GThreadPriority priority,
487 g_return_if_fail (func);
488 g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
489 g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
491 retval = g_new(GThreadData, 1);
495 retval->joinable = joinable;
497 retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
500 if (retval->thread == NULL)
502 gchar *win_error = g_win32_error_message (GetLastError ());
503 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
504 "Error creating thread: %s", win_error);
510 *(GThreadData **)thread = retval;
512 g_thread_set_priority_win32_impl (thread, priority);
516 g_thread_yield_win32_impl (void)
522 g_thread_join_win32_impl (gpointer thread)
524 GThreadData *target = *(GThreadData **)thread;
526 g_return_if_fail (target->joinable);
528 win32_check_for_error (WAIT_FAILED !=
529 WaitForSingleObject (target->thread, INFINITE));
531 win32_check_for_error (CloseHandle (target->thread));
535 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
537 static DWORD g_thread_xp_waiter_tls;
538 static CRITICAL_SECTION g_thread_xp_lock;
540 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
541 typedef struct _GThreadXpWaiter GThreadXpWaiter;
542 struct _GThreadXpWaiter
545 volatile GThreadXpWaiter *next;
548 static GThreadXpWaiter *
549 g_thread_xp_waiter_get (void)
551 GThreadXpWaiter *waiter;
553 waiter = TlsGetValue (g_thread_xp_waiter_tls);
555 if G_UNLIKELY (waiter == NULL)
557 waiter = malloc (sizeof (GThreadXpWaiter));
559 g_thread_abort (GetLastError (), "malloc");
560 waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
561 if (waiter->event == NULL)
562 g_thread_abort (GetLastError (), "CreateEvent");
564 TlsSetValue (g_thread_xp_waiter_tls, waiter);
571 g_thread_xp_CallThisOnThreadExit (void)
573 GThreadXpWaiter *waiter;
575 waiter = TlsGetValue (g_thread_xp_waiter_tls);
579 TlsSetValue (g_thread_xp_waiter_tls, NULL);
580 CloseHandle (waiter->event);
585 /* {{{2 SRWLock emulation */
588 CRITICAL_SECTION critical_section;
592 g_thread_xp_InitializeSRWLock (gpointer mutex)
594 *(GThreadSRWLock * volatile *) mutex = NULL;
598 g_thread_xp_DeleteSRWLock (gpointer mutex)
600 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
604 DeleteCriticalSection (&lock->critical_section);
609 static GThreadSRWLock *
610 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
612 GThreadSRWLock *result;
614 /* It looks like we're missing some barriers here, but this code only
615 * ever runs on Windows XP, which in turn only ever runs on hardware
616 * with a relatively rigid memory model. The 'volatile' will take
617 * care of the compiler.
621 if G_UNLIKELY (result == NULL)
623 EnterCriticalSection (&g_thread_xp_lock);
625 result = malloc (sizeof (GThreadSRWLock));
628 g_thread_abort (errno, "malloc");
630 InitializeCriticalSection (&result->critical_section);
633 LeaveCriticalSection (&g_thread_xp_lock);
640 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
642 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
644 EnterCriticalSection (&lock->critical_section);
648 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
650 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
652 return TryEnterCriticalSection (&lock->critical_section);
656 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
658 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
660 /* We need this until we fix some weird parts of GLib that try to
661 * unlock freshly-allocated mutexes.
664 LeaveCriticalSection (&lock->critical_section);
667 /* {{{2 CONDITION_VARIABLE emulation */
670 volatile GThreadXpWaiter *first;
671 volatile GThreadXpWaiter **last_ptr;
672 } GThreadXpCONDITION_VARIABLE;
675 g_thread_xp_InitializeConditionVariable (gpointer cond)
677 *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
681 g_thread_xp_DeleteConditionVariable (gpointer cond)
683 GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
689 static GThreadXpCONDITION_VARIABLE *
690 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
692 GThreadXpCONDITION_VARIABLE *result;
694 /* It looks like we're missing some barriers here, but this code only
695 * ever runs on Windows XP, which in turn only ever runs on hardware
696 * with a relatively rigid memory model. The 'volatile' will take
697 * care of the compiler.
701 if G_UNLIKELY (result == NULL)
703 result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
706 g_thread_abort (errno, "malloc");
708 result->first = NULL;
709 result->last_ptr = &result->first;
711 if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
722 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
727 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
728 GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
733 EnterCriticalSection (&g_thread_xp_lock);
734 *cv->last_ptr = waiter;
735 cv->last_ptr = &waiter->next;
736 LeaveCriticalSection (&g_thread_xp_lock);
738 g_mutex_unlock (mutex);
739 status = WaitForSingleObject (waiter->event, timeout);
741 if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
742 g_thread_abort (GetLastError (), "WaitForSingleObject");
744 g_mutex_lock (mutex);
746 return status == WAIT_OBJECT_0;
750 g_thread_xp_WakeConditionVariable (gpointer cond)
752 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
753 volatile GThreadXpWaiter *waiter;
755 EnterCriticalSection (&g_thread_xp_lock);
759 cv->first = waiter->next;
760 if (cv->first == NULL)
761 cv->last_ptr = &cv->first;
763 LeaveCriticalSection (&g_thread_xp_lock);
766 SetEvent (waiter->event);
770 g_thread_xp_WakeAllConditionVariable (gpointer cond)
772 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
773 volatile GThreadXpWaiter *waiter;
775 EnterCriticalSection (&g_thread_xp_lock);
778 cv->last_ptr = &cv->first;
779 LeaveCriticalSection (&g_thread_xp_lock);
781 while (waiter != NULL)
783 volatile GThreadXpWaiter *next;
786 SetEvent (waiter->event);
793 g_thread_xp_init (void)
795 static const GThreadImplVtable g_thread_xp_impl_vtable = {
796 g_thread_xp_CallThisOnThreadExit,
797 g_thread_xp_InitializeSRWLock,
798 g_thread_xp_DeleteSRWLock,
799 g_thread_xp_AcquireSRWLockExclusive,
800 g_thread_xp_TryAcquireSRWLockExclusive,
801 g_thread_xp_ReleaseSRWLockExclusive,
802 g_thread_xp_InitializeConditionVariable,
803 g_thread_xp_DeleteConditionVariable,
804 g_thread_xp_SleepConditionVariableSRW,
805 g_thread_xp_WakeAllConditionVariable,
806 g_thread_xp_WakeConditionVariable
809 InitializeCriticalSection (&g_thread_xp_lock);
810 g_thread_xp_waiter_tls = TlsAlloc ();
812 g_thread_impl_vtable = g_thread_xp_impl_vtable;
817 GThreadFunctions g_thread_functions_for_glib_use =
819 g_mutex_new, /* mutex */
824 g_cond_new, /* condition */
830 g_private_new_win32_impl, /* private thread data */
831 g_private_get_win32_impl,
832 g_private_set_win32_impl,
833 g_thread_create_win32_impl, /* thread */
834 g_thread_yield_win32_impl,
835 g_thread_join_win32_impl,
836 g_thread_exit_win32_impl,
837 g_thread_set_priority_win32_impl,
838 g_thread_self_win32_impl,
839 NULL /* no equal function necessary */
843 _g_thread_impl_init (void)
845 static gboolean beenhere = FALSE;
852 printf ("thread init\n");
853 win32_check_for_error (TLS_OUT_OF_INDEXES !=
854 (g_thread_self_tls = TlsAlloc ()));
855 win32_check_for_error (TLS_OUT_OF_INDEXES !=
856 (g_private_tls = TlsAlloc ()));
857 InitializeCriticalSection (&g_thread_global_spinlock);
861 g_thread_lookup_native_funcs (void)
863 GThreadImplVtable native_vtable = { 0, };
866 kernel32 = GetModuleHandle ("KERNEL32.DLL");
868 if (kernel32 == NULL)
871 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
872 GET_FUNC(InitializeSRWLock);
873 GET_FUNC(AcquireSRWLockExclusive);
874 GET_FUNC(TryAcquireSRWLockExclusive);
875 GET_FUNC(ReleaseSRWLockExclusive);
877 GET_FUNC(InitializeConditionVariable);
878 GET_FUNC(SleepConditionVariableSRW);
879 GET_FUNC(WakeAllConditionVariable);
880 GET_FUNC(WakeConditionVariable);
883 g_thread_impl_vtable = native_vtable;
889 g_thread_DllMain (void)
891 /* XXX This is broken right now for some unknown reason...
893 if (g_thread_lookup_native_funcs ())
894 fprintf (stderr, "(debug) GThread using native mode\n");
898 fprintf (stderr, "(debug) GThread using Windows XP mode\n");
903 /* vim:set foldmethod=marker: */