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);
109 void (__stdcall * AcquireSRWLockShared) (gpointer lock);
110 BOOLEAN (__stdcall * TryAcquireSRWLockShared) (gpointer lock);
111 void (__stdcall * ReleaseSRWLockShared) (gpointer lock);
113 void (__stdcall * InitializeConditionVariable) (gpointer cond);
114 void (__stdcall * DeleteConditionVariable) (gpointer cond); /* fake */
115 BOOL (__stdcall * SleepConditionVariableSRW) (gpointer cond,
119 void (__stdcall * WakeAllConditionVariable) (gpointer cond);
120 void (__stdcall * WakeConditionVariable) (gpointer cond);
123 static GThreadImplVtable g_thread_impl_vtable;
127 g_mutex_init (GMutex *mutex)
129 g_thread_impl_vtable.InitializeSRWLock (mutex);
133 g_mutex_clear (GMutex *mutex)
135 if (g_thread_impl_vtable.DeleteSRWLock != NULL)
136 g_thread_impl_vtable.DeleteSRWLock (mutex);
140 g_mutex_lock (GMutex *mutex)
142 g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
146 g_mutex_trylock (GMutex *mutex)
148 return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
152 g_mutex_unlock (GMutex *mutex)
154 g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
160 g_rw_lock_init (GRWLock *lock)
162 g_thread_impl_vtable.InitializeSRWLock (lock);
166 g_rw_lock_clear (GRWLock *lock)
168 if (g_thread_impl_vtable.DeleteSRWLock != NULL)
169 g_thread_impl_vtable.DeleteSRWLock (lock);
173 g_rw_lock_writer_lock (GRWLock *lock)
175 g_thread_impl_vtable.AcquireSRWLockExclusive (lock);
179 g_rw_lock_writer_trylock (GRWLock *lock)
181 return g_thread_impl_vtable.TryAcquireSRWLockExclusive (lock);
185 g_rw_lock_writer_unlock (GRWLock *lock)
187 g_thread_impl_vtable.ReleaseSRWLockExclusive (lock);
191 g_rw_lock_reader_lock (GRWLock *lock)
193 g_thread_impl_vtable.AcquireSRWLockShared (lock);
197 g_rw_lock_reader_trylock (GRWLock *lock)
199 return g_thread_impl_vtable.TryAcquireSRWLockShared (lock);
203 g_rw_lock_reader_unlock (GRWLock *lock)
205 g_thread_impl_vtable.ReleaseSRWLockShared (lock);
210 g_cond_init (GCond *cond)
212 g_thread_impl_vtable.InitializeConditionVariable (cond);
216 g_cond_clear (GCond *cond)
218 if (g_thread_impl_vtable.DeleteConditionVariable)
219 g_thread_impl_vtable.DeleteConditionVariable (cond);
223 g_cond_signal (GCond *cond)
225 g_thread_impl_vtable.WakeConditionVariable (cond);
229 g_cond_broadcast (GCond *cond)
231 g_thread_impl_vtable.WakeAllConditionVariable (cond);
235 g_cond_wait (GCond *cond,
236 GMutex *entered_mutex)
238 g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
242 g_cond_timedwait (GCond *cond,
243 GMutex *entered_mutex,
250 GetSystemTimeAsFileTime (&ft);
251 memmove (&now, &ft, sizeof (FILETIME));
253 now -= G_GINT64_CONSTANT (116444736000000000);
256 span = abs_time - now;
258 if G_UNLIKELY (span < 0)
261 if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
264 return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
268 g_cond_timed_wait (GCond *cond,
269 GMutex *entered_mutex,
276 micros = abs_time->tv_sec;
278 micros += abs_time->tv_usec;
280 return g_cond_timedwait (cond, entered_mutex, micros);
284 g_cond_wait (cond, entered_mutex);
291 typedef struct _GPrivateDestructor GPrivateDestructor;
293 struct _GPrivateDestructor
296 GDestroyNotify notify;
297 GPrivateDestructor *next;
300 static GPrivateDestructor * volatile g_private_destructors;
303 g_private_init (GPrivate *key,
304 GDestroyNotify notify)
306 GPrivateDestructor *destructor;
308 key->index = TlsAlloc ();
310 destructor = malloc (sizeof (GPrivateDestructor));
311 if G_UNLIKELY (destructor == NULL)
312 g_thread_abort (errno, "malloc");
313 destructor->index = key->index;
314 destructor->notify = notify;
317 destructor->next = g_private_destructors;
318 while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
324 g_private_get (GPrivate *key)
327 return key->single_value;
329 return TlsGetValue (key->index);
333 g_private_set (GPrivate *key,
338 key->single_value = value;
342 TlsSetValue (key->index, value);
348 #include "gthreadprivate.h"
350 #define win32_check_for_error(what) G_STMT_START{ \
352 g_error ("file %s: line %d (%s): error %s during %s", \
353 __FILE__, __LINE__, G_STRFUNC, \
354 g_win32_error_message (GetLastError ()), #what); \
357 #define G_MUTEX_SIZE (sizeof (gpointer))
359 static DWORD g_thread_self_tls;
360 static DWORD g_private_tls;
362 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
364 typedef struct _GThreadData GThreadData;
374 g_system_thread_self (gpointer thread)
376 GThreadData *self = TlsGetValue (g_thread_self_tls);
380 /* This should only happen for the main thread! */
381 HANDLE handle = GetCurrentThread ();
382 HANDLE process = GetCurrentProcess ();
383 self = g_new (GThreadData, 1);
384 win32_check_for_error (DuplicateHandle (process, handle, process,
385 &self->thread, 0, FALSE,
386 DUPLICATE_SAME_ACCESS));
387 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
390 self->joinable = FALSE;
393 *(GThreadData **)thread = self;
397 g_system_thread_exit (void)
399 GThreadData *self = TlsGetValue (g_thread_self_tls);
400 gboolean dtors_called;
404 GPrivateDestructor *dtor;
406 /* We go by the POSIX book on this one.
408 * If we call a destructor then there is a chance that some new
409 * TLS variables got set by code called in that destructor.
411 * Loop until nothing is left.
413 dtors_called = FALSE;
415 for (dtor = g_private_destructors; dtor; dtor = dtor->next)
419 value = TlsGetValue (dtor->index);
420 if (value != NULL && dtor->notify != NULL)
422 /* POSIX says to clear this before the call */
423 TlsSetValue (dtor->index, NULL);
424 dtor->notify (value);
429 while (dtors_called);
435 win32_check_for_error (CloseHandle (self->thread));
438 win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
441 if (g_thread_impl_vtable.CallThisOnThreadExit)
442 g_thread_impl_vtable.CallThisOnThreadExit ();
447 static guint __stdcall
448 g_thread_proxy (gpointer data)
450 GThreadData *self = (GThreadData*) data;
452 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
454 self->func (self->data);
456 g_system_thread_exit ();
458 g_assert_not_reached ();
464 g_system_thread_create (GThreadFunc func,
474 g_return_if_fail (func);
476 retval = g_new(GThreadData, 1);
480 retval->joinable = joinable;
482 retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
485 if (retval->thread == NULL)
487 gchar *win_error = g_win32_error_message (GetLastError ());
488 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
489 "Error creating thread: %s", win_error);
495 *(GThreadData **)thread = retval;
499 g_thread_yield (void)
505 g_system_thread_join (gpointer thread)
507 GThreadData *target = *(GThreadData **)thread;
509 g_return_if_fail (target->joinable);
511 win32_check_for_error (WAIT_FAILED !=
512 WaitForSingleObject (target->thread, INFINITE));
514 win32_check_for_error (CloseHandle (target->thread));
519 g_system_thread_equal (gpointer thread1,
522 return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
525 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
527 static CRITICAL_SECTION g_thread_xp_lock;
528 static DWORD g_thread_xp_waiter_tls;
530 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
531 typedef struct _GThreadXpWaiter GThreadXpWaiter;
532 struct _GThreadXpWaiter
535 volatile GThreadXpWaiter *next;
538 static GThreadXpWaiter *
539 g_thread_xp_waiter_get (void)
541 GThreadXpWaiter *waiter;
543 waiter = TlsGetValue (g_thread_xp_waiter_tls);
545 if G_UNLIKELY (waiter == NULL)
547 waiter = malloc (sizeof (GThreadXpWaiter));
549 g_thread_abort (GetLastError (), "malloc");
550 waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
551 if (waiter->event == NULL)
552 g_thread_abort (GetLastError (), "CreateEvent");
554 TlsSetValue (g_thread_xp_waiter_tls, waiter);
560 static void __stdcall
561 g_thread_xp_CallThisOnThreadExit (void)
563 GThreadXpWaiter *waiter;
565 waiter = TlsGetValue (g_thread_xp_waiter_tls);
569 TlsSetValue (g_thread_xp_waiter_tls, NULL);
570 CloseHandle (waiter->event);
575 /* {{{2 SRWLock emulation */
578 CRITICAL_SECTION writer_lock;
579 gboolean ever_shared; /* protected by writer_lock */
581 /* below is only ever touched if ever_shared becomes true */
582 CRITICAL_SECTION atomicity;
583 GThreadXpWaiter *queued_writer; /* protected by atomicity lock */
584 gint num_readers; /* protected by atomicity lock */
587 static void __stdcall
588 g_thread_xp_InitializeSRWLock (gpointer mutex)
590 *(GThreadSRWLock * volatile *) mutex = NULL;
593 static void __stdcall
594 g_thread_xp_DeleteSRWLock (gpointer mutex)
596 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
600 if (lock->ever_shared)
601 DeleteCriticalSection (&lock->atomicity);
603 DeleteCriticalSection (&lock->writer_lock);
608 static GThreadSRWLock * __stdcall
609 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
611 GThreadSRWLock *result;
613 /* It looks like we're missing some barriers here, but this code only
614 * ever runs on Windows XP, which in turn only ever runs on hardware
615 * with a relatively rigid memory model. The 'volatile' will take
616 * care of the compiler.
620 if G_UNLIKELY (result == NULL)
622 EnterCriticalSection (&g_thread_xp_lock);
624 result = malloc (sizeof (GThreadSRWLock));
627 g_thread_abort (errno, "malloc");
629 InitializeCriticalSection (&result->writer_lock);
630 result->ever_shared = FALSE;
633 LeaveCriticalSection (&g_thread_xp_lock);
639 static void __stdcall
640 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
642 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
644 EnterCriticalSection (&lock->writer_lock);
646 if (lock->ever_shared)
648 GThreadXpWaiter *waiter = NULL;
650 EnterCriticalSection (&lock->atomicity);
651 if (lock->num_readers > 0)
652 lock->queued_writer = waiter = g_thread_xp_waiter_get ();
653 LeaveCriticalSection (&lock->atomicity);
656 WaitForSingleObject (waiter->event, INFINITE);
658 lock->queued_writer = NULL;
662 static BOOLEAN __stdcall
663 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
665 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
667 if (!TryEnterCriticalSection (&lock->writer_lock))
670 if (lock->ever_shared)
674 EnterCriticalSection (&lock->atomicity);
675 available = lock->num_readers == 0;
676 LeaveCriticalSection (&lock->atomicity);
680 LeaveCriticalSection (&lock->writer_lock);
688 static void __stdcall
689 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
691 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
693 /* We need this until we fix some weird parts of GLib that try to
694 * unlock freshly-allocated mutexes.
697 LeaveCriticalSection (&lock->writer_lock);
701 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
703 if G_UNLIKELY (!lock->ever_shared)
705 InitializeCriticalSection (&lock->atomicity);
706 lock->queued_writer = NULL;
707 lock->num_readers = 0;
709 lock->ever_shared = TRUE;
712 EnterCriticalSection (&lock->atomicity);
714 LeaveCriticalSection (&lock->atomicity);
717 static void __stdcall
718 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
720 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
722 EnterCriticalSection (&lock->writer_lock);
724 g_thread_xp_srwlock_become_reader (lock);
726 LeaveCriticalSection (&lock->writer_lock);
729 static BOOLEAN __stdcall
730 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
732 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
734 if (!TryEnterCriticalSection (&lock->writer_lock))
737 g_thread_xp_srwlock_become_reader (lock);
739 LeaveCriticalSection (&lock->writer_lock);
744 static void __stdcall
745 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
747 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
749 EnterCriticalSection (&lock->atomicity);
753 if (lock->num_readers == 0 && lock->queued_writer)
754 SetEvent (lock->queued_writer->event);
756 LeaveCriticalSection (&lock->atomicity);
759 /* {{{2 CONDITION_VARIABLE emulation */
762 volatile GThreadXpWaiter *first;
763 volatile GThreadXpWaiter **last_ptr;
764 } GThreadXpCONDITION_VARIABLE;
766 static void __stdcall
767 g_thread_xp_InitializeConditionVariable (gpointer cond)
769 *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
772 static void __stdcall
773 g_thread_xp_DeleteConditionVariable (gpointer cond)
775 GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
781 static GThreadXpCONDITION_VARIABLE * __stdcall
782 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
784 GThreadXpCONDITION_VARIABLE *result;
786 /* It looks like we're missing some barriers here, but this code only
787 * ever runs on Windows XP, which in turn only ever runs on hardware
788 * with a relatively rigid memory model. The 'volatile' will take
789 * care of the compiler.
793 if G_UNLIKELY (result == NULL)
795 result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
798 g_thread_abort (errno, "malloc");
800 result->first = NULL;
801 result->last_ptr = &result->first;
803 if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
813 static BOOL __stdcall
814 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
819 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
820 GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
825 EnterCriticalSection (&g_thread_xp_lock);
826 *cv->last_ptr = waiter;
827 cv->last_ptr = &waiter->next;
828 LeaveCriticalSection (&g_thread_xp_lock);
830 g_mutex_unlock (mutex);
831 status = WaitForSingleObject (waiter->event, timeout);
833 if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
834 g_thread_abort (GetLastError (), "WaitForSingleObject");
836 g_mutex_lock (mutex);
838 return status == WAIT_OBJECT_0;
841 static void __stdcall
842 g_thread_xp_WakeConditionVariable (gpointer cond)
844 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
845 volatile GThreadXpWaiter *waiter;
847 EnterCriticalSection (&g_thread_xp_lock);
851 cv->first = waiter->next;
852 if (cv->first == NULL)
853 cv->last_ptr = &cv->first;
855 LeaveCriticalSection (&g_thread_xp_lock);
858 SetEvent (waiter->event);
861 static void __stdcall
862 g_thread_xp_WakeAllConditionVariable (gpointer cond)
864 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
865 volatile GThreadXpWaiter *waiter;
867 EnterCriticalSection (&g_thread_xp_lock);
870 cv->last_ptr = &cv->first;
871 LeaveCriticalSection (&g_thread_xp_lock);
873 while (waiter != NULL)
875 volatile GThreadXpWaiter *next;
878 SetEvent (waiter->event);
885 g_thread_xp_init (void)
887 static const GThreadImplVtable g_thread_xp_impl_vtable = {
888 g_thread_xp_CallThisOnThreadExit,
889 g_thread_xp_InitializeSRWLock,
890 g_thread_xp_DeleteSRWLock,
891 g_thread_xp_AcquireSRWLockExclusive,
892 g_thread_xp_TryAcquireSRWLockExclusive,
893 g_thread_xp_ReleaseSRWLockExclusive,
894 g_thread_xp_AcquireSRWLockShared,
895 g_thread_xp_TryAcquireSRWLockShared,
896 g_thread_xp_ReleaseSRWLockShared,
897 g_thread_xp_InitializeConditionVariable,
898 g_thread_xp_DeleteConditionVariable,
899 g_thread_xp_SleepConditionVariableSRW,
900 g_thread_xp_WakeAllConditionVariable,
901 g_thread_xp_WakeConditionVariable
904 InitializeCriticalSection (&g_thread_xp_lock);
905 g_thread_xp_waiter_tls = TlsAlloc ();
907 g_thread_impl_vtable = g_thread_xp_impl_vtable;
913 g_thread_lookup_native_funcs (void)
915 GThreadImplVtable native_vtable = { 0, };
918 kernel32 = GetModuleHandle ("KERNEL32.DLL");
920 if (kernel32 == NULL)
923 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
924 GET_FUNC(InitializeSRWLock);
925 GET_FUNC(AcquireSRWLockExclusive);
926 GET_FUNC(TryAcquireSRWLockExclusive);
927 GET_FUNC(ReleaseSRWLockExclusive);
928 GET_FUNC(AcquireSRWLockShared);
929 GET_FUNC(TryAcquireSRWLockShared);
930 GET_FUNC(ReleaseSRWLockShared);
932 GET_FUNC(InitializeConditionVariable);
933 GET_FUNC(SleepConditionVariableSRW);
934 GET_FUNC(WakeAllConditionVariable);
935 GET_FUNC(WakeConditionVariable);
938 g_thread_impl_vtable = native_vtable;
944 g_thread_DllMain (void)
946 if (g_thread_lookup_native_funcs ())
947 fprintf (stderr, "(debug) GThread using native mode\n");
950 fprintf (stderr, "(debug) GThread using Windows XP mode\n");
954 win32_check_for_error (TLS_OUT_OF_INDEXES != (g_thread_self_tls = TlsAlloc ()));
955 win32_check_for_error (TLS_OUT_OF_INDEXES != (g_private_tls = TlsAlloc ()));
958 /* vim:set foldmethod=marker: */