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.
46 #include "gthreadprivate.h"
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 (__stdcall * CallThisOnThreadExit) (void); /* fake */
104 void (__stdcall * InitializeSRWLock) (gpointer lock);
105 void (__stdcall * DeleteSRWLock) (gpointer lock); /* fake */
106 void (__stdcall * AcquireSRWLockExclusive) (gpointer lock);
107 BOOLEAN (__stdcall * TryAcquireSRWLockExclusive) (gpointer lock);
108 void (__stdcall * ReleaseSRWLockExclusive) (gpointer lock);
110 void (__stdcall * InitializeConditionVariable) (gpointer cond);
111 void (__stdcall * DeleteConditionVariable) (gpointer cond); /* fake */
112 BOOL (__stdcall * SleepConditionVariableSRW) (gpointer cond,
116 void (__stdcall * WakeAllConditionVariable) (gpointer cond);
117 void (__stdcall * 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 g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
143 g_mutex_trylock (GMutex *mutex)
145 return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
149 g_mutex_unlock (GMutex *mutex)
151 g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
156 g_cond_init (GCond *cond)
158 g_thread_impl_vtable.InitializeConditionVariable (cond);
162 g_cond_clear (GCond *cond)
164 if (g_thread_impl_vtable.DeleteConditionVariable)
165 g_thread_impl_vtable.DeleteConditionVariable (cond);
169 g_cond_signal (GCond *cond)
171 g_thread_impl_vtable.WakeConditionVariable (cond);
175 g_cond_broadcast (GCond *cond)
177 g_thread_impl_vtable.WakeAllConditionVariable (cond);
181 g_cond_wait (GCond *cond,
182 GMutex *entered_mutex)
184 g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
188 g_cond_timedwait (GCond *cond,
189 GMutex *entered_mutex,
196 GetSystemTimeAsFileTime (&ft);
197 memmove (&now, &ft, sizeof (FILETIME));
199 now -= G_GINT64_CONSTANT (116444736000000000);
202 span = abs_time - now;
204 if G_UNLIKELY (span < 0)
207 if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
210 return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
214 g_cond_timed_wait (GCond *cond,
215 GMutex *entered_mutex,
222 micros = abs_time->tv_sec;
224 micros += abs_time->tv_usec;
226 return g_cond_timedwait (cond, entered_mutex, micros);
230 g_cond_wait (cond, entered_mutex);
237 typedef struct _GPrivateDestructor GPrivateDestructor;
239 struct _GPrivateDestructor
242 GDestroyNotify notify;
243 GPrivateDestructor *next;
246 static GPrivateDestructor * volatile g_private_destructors;
249 g_private_init (GPrivate *key,
250 GDestroyNotify notify)
252 GPrivateDestructor *destructor;
254 key->index = TlsAlloc ();
256 destructor = malloc (sizeof (GPrivateDestructor));
257 if G_UNLIKELY (destructor == NULL)
258 g_thread_abort (errno, "malloc");
259 destructor->index = key->index;
260 destructor->notify = notify;
263 destructor->next = g_private_destructors;
264 while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
270 g_private_get (GPrivate *key)
273 return key->single_value;
275 return TlsGetValue (key->index);
279 g_private_set (GPrivate *key,
284 key->single_value = value;
288 TlsSetValue (key->index, value);
294 #include "gthreadprivate.h"
296 #define win32_check_for_error(what) G_STMT_START{ \
298 g_error ("file %s: line %d (%s): error %s during %s", \
299 __FILE__, __LINE__, G_STRFUNC, \
300 g_win32_error_message (GetLastError ()), #what); \
303 #define G_MUTEX_SIZE (sizeof (gpointer))
305 static DWORD g_thread_self_tls;
306 static DWORD g_private_tls;
308 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
310 typedef struct _GThreadData GThreadData;
320 g_system_thread_self (gpointer thread)
322 GThreadData *self = TlsGetValue (g_thread_self_tls);
326 /* This should only happen for the main thread! */
327 HANDLE handle = GetCurrentThread ();
328 HANDLE process = GetCurrentProcess ();
329 self = g_new (GThreadData, 1);
330 win32_check_for_error (DuplicateHandle (process, handle, process,
331 &self->thread, 0, FALSE,
332 DUPLICATE_SAME_ACCESS));
333 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
336 self->joinable = FALSE;
339 *(GThreadData **)thread = self;
343 g_system_thread_exit (void)
345 GThreadData *self = TlsGetValue (g_thread_self_tls);
346 gboolean dtors_called;
350 GPrivateDestructor *dtor;
352 /* We go by the POSIX book on this one.
354 * If we call a destructor then there is a chance that some new
355 * TLS variables got set by code called in that destructor.
357 * Loop until nothing is left.
359 dtors_called = FALSE;
361 for (dtor = g_private_destructors; dtor; dtor = dtor->next)
365 value = TlsGetValue (dtor->index);
366 if (value != NULL && dtor->notify != NULL)
368 /* POSIX says to clear this before the call */
369 TlsSetValue (dtor->index, NULL);
370 dtor->notify (value);
375 while (dtors_called);
381 win32_check_for_error (CloseHandle (self->thread));
384 win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
387 if (g_thread_impl_vtable.CallThisOnThreadExit)
388 g_thread_impl_vtable.CallThisOnThreadExit ();
393 static guint __stdcall
394 g_thread_proxy (gpointer data)
396 GThreadData *self = (GThreadData*) data;
398 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
400 self->func (self->data);
402 g_system_thread_exit ();
404 g_assert_not_reached ();
410 g_system_thread_create (GThreadFunc func,
420 g_return_if_fail (func);
422 retval = g_new(GThreadData, 1);
426 retval->joinable = joinable;
428 retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
431 if (retval->thread == NULL)
433 gchar *win_error = g_win32_error_message (GetLastError ());
434 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
435 "Error creating thread: %s", win_error);
441 *(GThreadData **)thread = retval;
445 g_thread_yield (void)
451 g_system_thread_join (gpointer thread)
453 GThreadData *target = *(GThreadData **)thread;
455 g_return_if_fail (target->joinable);
457 win32_check_for_error (WAIT_FAILED !=
458 WaitForSingleObject (target->thread, INFINITE));
460 win32_check_for_error (CloseHandle (target->thread));
465 g_system_thread_equal (gpointer thread1,
468 return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
471 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
473 static CRITICAL_SECTION g_thread_xp_lock;
474 static DWORD g_thread_xp_waiter_tls;
476 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
477 typedef struct _GThreadXpWaiter GThreadXpWaiter;
478 struct _GThreadXpWaiter
481 volatile GThreadXpWaiter *next;
484 static GThreadXpWaiter *
485 g_thread_xp_waiter_get (void)
487 GThreadXpWaiter *waiter;
489 waiter = TlsGetValue (g_thread_xp_waiter_tls);
491 if G_UNLIKELY (waiter == NULL)
493 waiter = malloc (sizeof (GThreadXpWaiter));
495 g_thread_abort (GetLastError (), "malloc");
496 waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
497 if (waiter->event == NULL)
498 g_thread_abort (GetLastError (), "CreateEvent");
500 TlsSetValue (g_thread_xp_waiter_tls, waiter);
506 static void __stdcall
507 g_thread_xp_CallThisOnThreadExit (void)
509 GThreadXpWaiter *waiter;
511 waiter = TlsGetValue (g_thread_xp_waiter_tls);
515 TlsSetValue (g_thread_xp_waiter_tls, NULL);
516 CloseHandle (waiter->event);
521 /* {{{2 SRWLock emulation */
524 CRITICAL_SECTION writer_lock;
527 static void __stdcall
528 g_thread_xp_InitializeSRWLock (gpointer mutex)
530 *(GThreadSRWLock * volatile *) mutex = NULL;
533 static void __stdcall
534 g_thread_xp_DeleteSRWLock (gpointer mutex)
536 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
540 DeleteCriticalSection (&lock->writer_lock);
545 static GThreadSRWLock * __stdcall
546 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
548 GThreadSRWLock *result;
550 /* It looks like we're missing some barriers here, but this code only
551 * ever runs on Windows XP, which in turn only ever runs on hardware
552 * with a relatively rigid memory model. The 'volatile' will take
553 * care of the compiler.
557 if G_UNLIKELY (result == NULL)
559 EnterCriticalSection (&g_thread_xp_lock);
561 result = malloc (sizeof (GThreadSRWLock));
564 g_thread_abort (errno, "malloc");
566 InitializeCriticalSection (&result->writer_lock);
569 LeaveCriticalSection (&g_thread_xp_lock);
575 static void __stdcall
576 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
578 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
580 EnterCriticalSection (&lock->writer_lock);
583 static BOOLEAN __stdcall
584 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
586 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
588 return TryEnterCriticalSection (&lock->writer_lock);
591 static void __stdcall
592 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
594 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
596 /* We need this until we fix some weird parts of GLib that try to
597 * unlock freshly-allocated mutexes.
600 LeaveCriticalSection (&lock->writer_lock);
603 /* {{{2 CONDITION_VARIABLE emulation */
606 volatile GThreadXpWaiter *first;
607 volatile GThreadXpWaiter **last_ptr;
608 } GThreadXpCONDITION_VARIABLE;
610 static void __stdcall
611 g_thread_xp_InitializeConditionVariable (gpointer cond)
613 *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
616 static void __stdcall
617 g_thread_xp_DeleteConditionVariable (gpointer cond)
619 GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
625 static GThreadXpCONDITION_VARIABLE * __stdcall
626 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
628 GThreadXpCONDITION_VARIABLE *result;
630 /* It looks like we're missing some barriers here, but this code only
631 * ever runs on Windows XP, which in turn only ever runs on hardware
632 * with a relatively rigid memory model. The 'volatile' will take
633 * care of the compiler.
637 if G_UNLIKELY (result == NULL)
639 result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
642 g_thread_abort (errno, "malloc");
644 result->first = NULL;
645 result->last_ptr = &result->first;
647 if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
657 static BOOL __stdcall
658 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
663 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
664 GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
669 EnterCriticalSection (&g_thread_xp_lock);
670 *cv->last_ptr = waiter;
671 cv->last_ptr = &waiter->next;
672 LeaveCriticalSection (&g_thread_xp_lock);
674 g_mutex_unlock (mutex);
675 status = WaitForSingleObject (waiter->event, timeout);
677 if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
678 g_thread_abort (GetLastError (), "WaitForSingleObject");
680 g_mutex_lock (mutex);
682 return status == WAIT_OBJECT_0;
685 static void __stdcall
686 g_thread_xp_WakeConditionVariable (gpointer cond)
688 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
689 volatile GThreadXpWaiter *waiter;
691 EnterCriticalSection (&g_thread_xp_lock);
695 cv->first = waiter->next;
696 if (cv->first == NULL)
697 cv->last_ptr = &cv->first;
699 LeaveCriticalSection (&g_thread_xp_lock);
702 SetEvent (waiter->event);
705 static void __stdcall
706 g_thread_xp_WakeAllConditionVariable (gpointer cond)
708 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
709 volatile GThreadXpWaiter *waiter;
711 EnterCriticalSection (&g_thread_xp_lock);
714 cv->last_ptr = &cv->first;
715 LeaveCriticalSection (&g_thread_xp_lock);
717 while (waiter != NULL)
719 volatile GThreadXpWaiter *next;
722 SetEvent (waiter->event);
729 g_thread_xp_init (void)
731 static const GThreadImplVtable g_thread_xp_impl_vtable = {
732 g_thread_xp_CallThisOnThreadExit,
733 g_thread_xp_InitializeSRWLock,
734 g_thread_xp_DeleteSRWLock,
735 g_thread_xp_AcquireSRWLockExclusive,
736 g_thread_xp_TryAcquireSRWLockExclusive,
737 g_thread_xp_ReleaseSRWLockExclusive,
738 g_thread_xp_InitializeConditionVariable,
739 g_thread_xp_DeleteConditionVariable,
740 g_thread_xp_SleepConditionVariableSRW,
741 g_thread_xp_WakeAllConditionVariable,
742 g_thread_xp_WakeConditionVariable
745 InitializeCriticalSection (&g_thread_xp_lock);
746 g_thread_xp_waiter_tls = TlsAlloc ();
748 g_thread_impl_vtable = g_thread_xp_impl_vtable;
754 _g_thread_impl_init (void)
756 static gboolean beenhere = FALSE;
763 printf ("thread init\n");
764 win32_check_for_error (TLS_OUT_OF_INDEXES !=
765 (g_thread_self_tls = TlsAlloc ()));
766 win32_check_for_error (TLS_OUT_OF_INDEXES !=
767 (g_private_tls = TlsAlloc ()));
771 g_thread_lookup_native_funcs (void)
773 GThreadImplVtable native_vtable = { 0, };
776 kernel32 = GetModuleHandle ("KERNEL32.DLL");
778 if (kernel32 == NULL)
781 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
782 GET_FUNC(InitializeSRWLock);
783 GET_FUNC(AcquireSRWLockExclusive);
784 GET_FUNC(TryAcquireSRWLockExclusive);
785 GET_FUNC(ReleaseSRWLockExclusive);
787 GET_FUNC(InitializeConditionVariable);
788 GET_FUNC(SleepConditionVariableSRW);
789 GET_FUNC(WakeAllConditionVariable);
790 GET_FUNC(WakeConditionVariable);
793 g_thread_impl_vtable = native_vtable;
799 g_thread_DllMain (void)
801 if (g_thread_lookup_native_funcs ())
802 fprintf (stderr, "(debug) GThread using native mode\n");
805 fprintf (stderr, "(debug) GThread using Windows XP mode\n");
810 /* vim:set foldmethod=marker: */