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);
159 g_cond_init (GCond *cond)
161 g_thread_impl_vtable.InitializeConditionVariable (cond);
165 g_cond_clear (GCond *cond)
167 if (g_thread_impl_vtable.DeleteConditionVariable)
168 g_thread_impl_vtable.DeleteConditionVariable (cond);
172 g_cond_signal (GCond *cond)
174 g_thread_impl_vtable.WakeConditionVariable (cond);
178 g_cond_broadcast (GCond *cond)
180 g_thread_impl_vtable.WakeAllConditionVariable (cond);
184 g_cond_wait (GCond *cond,
185 GMutex *entered_mutex)
187 g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
191 g_cond_timedwait (GCond *cond,
192 GMutex *entered_mutex,
199 GetSystemTimeAsFileTime (&ft);
200 memmove (&now, &ft, sizeof (FILETIME));
202 now -= G_GINT64_CONSTANT (116444736000000000);
205 span = abs_time - now;
207 if G_UNLIKELY (span < 0)
210 if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
213 return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
217 g_cond_timed_wait (GCond *cond,
218 GMutex *entered_mutex,
225 micros = abs_time->tv_sec;
227 micros += abs_time->tv_usec;
229 return g_cond_timedwait (cond, entered_mutex, micros);
233 g_cond_wait (cond, entered_mutex);
240 typedef struct _GPrivateDestructor GPrivateDestructor;
242 struct _GPrivateDestructor
245 GDestroyNotify notify;
246 GPrivateDestructor *next;
249 static GPrivateDestructor * volatile g_private_destructors;
252 g_private_init (GPrivate *key,
253 GDestroyNotify notify)
255 GPrivateDestructor *destructor;
257 key->index = TlsAlloc ();
259 destructor = malloc (sizeof (GPrivateDestructor));
260 if G_UNLIKELY (destructor == NULL)
261 g_thread_abort (errno, "malloc");
262 destructor->index = key->index;
263 destructor->notify = notify;
266 destructor->next = g_private_destructors;
267 while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
273 g_private_get (GPrivate *key)
276 return key->single_value;
278 return TlsGetValue (key->index);
282 g_private_set (GPrivate *key,
287 key->single_value = value;
291 TlsSetValue (key->index, value);
297 #include "gthreadprivate.h"
299 #define win32_check_for_error(what) G_STMT_START{ \
301 g_error ("file %s: line %d (%s): error %s during %s", \
302 __FILE__, __LINE__, G_STRFUNC, \
303 g_win32_error_message (GetLastError ()), #what); \
306 #define G_MUTEX_SIZE (sizeof (gpointer))
308 static DWORD g_thread_self_tls;
309 static DWORD g_private_tls;
311 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
313 typedef struct _GThreadData GThreadData;
323 g_system_thread_self (gpointer thread)
325 GThreadData *self = TlsGetValue (g_thread_self_tls);
329 /* This should only happen for the main thread! */
330 HANDLE handle = GetCurrentThread ();
331 HANDLE process = GetCurrentProcess ();
332 self = g_new (GThreadData, 1);
333 win32_check_for_error (DuplicateHandle (process, handle, process,
334 &self->thread, 0, FALSE,
335 DUPLICATE_SAME_ACCESS));
336 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
339 self->joinable = FALSE;
342 *(GThreadData **)thread = self;
346 g_system_thread_exit (void)
348 GThreadData *self = TlsGetValue (g_thread_self_tls);
349 gboolean dtors_called;
353 GPrivateDestructor *dtor;
355 /* We go by the POSIX book on this one.
357 * If we call a destructor then there is a chance that some new
358 * TLS variables got set by code called in that destructor.
360 * Loop until nothing is left.
362 dtors_called = FALSE;
364 for (dtor = g_private_destructors; dtor; dtor = dtor->next)
368 value = TlsGetValue (dtor->index);
369 if (value != NULL && dtor->notify != NULL)
371 /* POSIX says to clear this before the call */
372 TlsSetValue (dtor->index, NULL);
373 dtor->notify (value);
378 while (dtors_called);
384 win32_check_for_error (CloseHandle (self->thread));
387 win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
390 if (g_thread_impl_vtable.CallThisOnThreadExit)
391 g_thread_impl_vtable.CallThisOnThreadExit ();
396 static guint __stdcall
397 g_thread_proxy (gpointer data)
399 GThreadData *self = (GThreadData*) data;
401 win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
403 self->func (self->data);
405 g_system_thread_exit ();
407 g_assert_not_reached ();
413 g_system_thread_create (GThreadFunc func,
423 g_return_if_fail (func);
425 retval = g_new(GThreadData, 1);
429 retval->joinable = joinable;
431 retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
434 if (retval->thread == NULL)
436 gchar *win_error = g_win32_error_message (GetLastError ());
437 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
438 "Error creating thread: %s", win_error);
444 *(GThreadData **)thread = retval;
448 g_thread_yield (void)
454 g_system_thread_join (gpointer thread)
456 GThreadData *target = *(GThreadData **)thread;
458 g_return_if_fail (target->joinable);
460 win32_check_for_error (WAIT_FAILED !=
461 WaitForSingleObject (target->thread, INFINITE));
463 win32_check_for_error (CloseHandle (target->thread));
468 g_system_thread_equal (gpointer thread1,
471 return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
474 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
476 static CRITICAL_SECTION g_thread_xp_lock;
477 static DWORD g_thread_xp_waiter_tls;
479 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
480 typedef struct _GThreadXpWaiter GThreadXpWaiter;
481 struct _GThreadXpWaiter
484 volatile GThreadXpWaiter *next;
487 static GThreadXpWaiter *
488 g_thread_xp_waiter_get (void)
490 GThreadXpWaiter *waiter;
492 waiter = TlsGetValue (g_thread_xp_waiter_tls);
494 if G_UNLIKELY (waiter == NULL)
496 waiter = malloc (sizeof (GThreadXpWaiter));
498 g_thread_abort (GetLastError (), "malloc");
499 waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
500 if (waiter->event == NULL)
501 g_thread_abort (GetLastError (), "CreateEvent");
503 TlsSetValue (g_thread_xp_waiter_tls, waiter);
509 static void __stdcall
510 g_thread_xp_CallThisOnThreadExit (void)
512 GThreadXpWaiter *waiter;
514 waiter = TlsGetValue (g_thread_xp_waiter_tls);
518 TlsSetValue (g_thread_xp_waiter_tls, NULL);
519 CloseHandle (waiter->event);
524 /* {{{2 SRWLock emulation */
527 CRITICAL_SECTION writer_lock;
528 gboolean ever_shared; /* protected by writer_lock */
530 /* below is only ever touched if ever_shared becomes true */
531 CRITICAL_SECTION atomicity;
532 GThreadXpWaiter *queued_writer; /* protected by atomicity lock */
533 gint num_readers; /* protected by atomicity lock */
536 static void __stdcall
537 g_thread_xp_InitializeSRWLock (gpointer mutex)
539 *(GThreadSRWLock * volatile *) mutex = NULL;
542 static void __stdcall
543 g_thread_xp_DeleteSRWLock (gpointer mutex)
545 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
549 if (lock->ever_shared)
550 DeleteCriticalSection (&lock->atomicity);
552 DeleteCriticalSection (&lock->writer_lock);
557 static GThreadSRWLock * __stdcall
558 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
560 GThreadSRWLock *result;
562 /* It looks like we're missing some barriers here, but this code only
563 * ever runs on Windows XP, which in turn only ever runs on hardware
564 * with a relatively rigid memory model. The 'volatile' will take
565 * care of the compiler.
569 if G_UNLIKELY (result == NULL)
571 EnterCriticalSection (&g_thread_xp_lock);
573 result = malloc (sizeof (GThreadSRWLock));
576 g_thread_abort (errno, "malloc");
578 InitializeCriticalSection (&result->writer_lock);
579 result->ever_shared = FALSE;
582 LeaveCriticalSection (&g_thread_xp_lock);
588 static void __stdcall
589 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
591 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
593 EnterCriticalSection (&lock->writer_lock);
595 if (lock->ever_shared)
597 GThreadXpWaiter *waiter = NULL;
599 EnterCriticalSection (&lock->atomicity);
600 if (lock->num_readers > 0)
601 lock->queued_writer = waiter = g_thread_xp_waiter_get ();
602 LeaveCriticalSection (&lock->atomicity);
605 WaitForSingleObject (waiter->event, INFINITE);
607 lock->queued_writer = NULL;
611 static BOOLEAN __stdcall
612 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
614 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
616 if (!TryEnterCriticalSection (&lock->writer_lock))
619 if (lock->ever_shared)
623 EnterCriticalSection (&lock->atomicity);
624 available = lock->num_readers == 0;
625 LeaveCriticalSection (&lock->atomicity);
629 LeaveCriticalSection (&lock->writer_lock);
637 static void __stdcall
638 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
640 GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
642 /* We need this until we fix some weird parts of GLib that try to
643 * unlock freshly-allocated mutexes.
646 LeaveCriticalSection (&lock->writer_lock);
650 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
652 if G_UNLIKELY (!lock->ever_shared)
654 InitializeCriticalSection (&lock->atomicity);
655 lock->queued_writer = NULL;
656 lock->num_readers = 0;
658 lock->ever_shared = TRUE;
661 EnterCriticalSection (&lock->atomicity);
663 LeaveCriticalSection (&lock->atomicity);
666 static void __stdcall
667 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
669 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
671 EnterCriticalSection (&lock->writer_lock);
673 g_thread_xp_srwlock_become_reader (lock);
675 LeaveCriticalSection (&lock->writer_lock);
678 static BOOLEAN __stdcall
679 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
681 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
683 if (!TryEnterCriticalSection (&lock->writer_lock))
686 g_thread_xp_srwlock_become_reader (lock);
688 LeaveCriticalSection (&lock->writer_lock);
693 static void __stdcall
694 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
696 GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
698 EnterCriticalSection (&lock->atomicity);
702 if (lock->num_readers == 0 && lock->queued_writer)
703 SetEvent (lock->queued_writer->event);
705 LeaveCriticalSection (&lock->atomicity);
708 /* {{{2 CONDITION_VARIABLE emulation */
711 volatile GThreadXpWaiter *first;
712 volatile GThreadXpWaiter **last_ptr;
713 } GThreadXpCONDITION_VARIABLE;
715 static void __stdcall
716 g_thread_xp_InitializeConditionVariable (gpointer cond)
718 *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
721 static void __stdcall
722 g_thread_xp_DeleteConditionVariable (gpointer cond)
724 GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
730 static GThreadXpCONDITION_VARIABLE * __stdcall
731 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
733 GThreadXpCONDITION_VARIABLE *result;
735 /* It looks like we're missing some barriers here, but this code only
736 * ever runs on Windows XP, which in turn only ever runs on hardware
737 * with a relatively rigid memory model. The 'volatile' will take
738 * care of the compiler.
742 if G_UNLIKELY (result == NULL)
744 result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
747 g_thread_abort (errno, "malloc");
749 result->first = NULL;
750 result->last_ptr = &result->first;
752 if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
762 static BOOL __stdcall
763 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
768 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
769 GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
774 EnterCriticalSection (&g_thread_xp_lock);
775 *cv->last_ptr = waiter;
776 cv->last_ptr = &waiter->next;
777 LeaveCriticalSection (&g_thread_xp_lock);
779 g_mutex_unlock (mutex);
780 status = WaitForSingleObject (waiter->event, timeout);
782 if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
783 g_thread_abort (GetLastError (), "WaitForSingleObject");
785 g_mutex_lock (mutex);
787 return status == WAIT_OBJECT_0;
790 static void __stdcall
791 g_thread_xp_WakeConditionVariable (gpointer cond)
793 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
794 volatile GThreadXpWaiter *waiter;
796 EnterCriticalSection (&g_thread_xp_lock);
800 cv->first = waiter->next;
801 if (cv->first == NULL)
802 cv->last_ptr = &cv->first;
804 LeaveCriticalSection (&g_thread_xp_lock);
807 SetEvent (waiter->event);
810 static void __stdcall
811 g_thread_xp_WakeAllConditionVariable (gpointer cond)
813 GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
814 volatile GThreadXpWaiter *waiter;
816 EnterCriticalSection (&g_thread_xp_lock);
819 cv->last_ptr = &cv->first;
820 LeaveCriticalSection (&g_thread_xp_lock);
822 while (waiter != NULL)
824 volatile GThreadXpWaiter *next;
827 SetEvent (waiter->event);
834 g_thread_xp_init (void)
836 static const GThreadImplVtable g_thread_xp_impl_vtable = {
837 g_thread_xp_CallThisOnThreadExit,
838 g_thread_xp_InitializeSRWLock,
839 g_thread_xp_DeleteSRWLock,
840 g_thread_xp_AcquireSRWLockExclusive,
841 g_thread_xp_TryAcquireSRWLockExclusive,
842 g_thread_xp_ReleaseSRWLockExclusive,
843 g_thread_xp_AcquireSRWLockShared,
844 g_thread_xp_TryAcquireSRWLockShared,
845 g_thread_xp_ReleaseSRWLockShared,
846 g_thread_xp_InitializeConditionVariable,
847 g_thread_xp_DeleteConditionVariable,
848 g_thread_xp_SleepConditionVariableSRW,
849 g_thread_xp_WakeAllConditionVariable,
850 g_thread_xp_WakeConditionVariable
853 InitializeCriticalSection (&g_thread_xp_lock);
854 g_thread_xp_waiter_tls = TlsAlloc ();
856 g_thread_impl_vtable = g_thread_xp_impl_vtable;
862 _g_thread_impl_init (void)
864 static gboolean beenhere = FALSE;
871 printf ("thread init\n");
872 win32_check_for_error (TLS_OUT_OF_INDEXES !=
873 (g_thread_self_tls = TlsAlloc ()));
874 win32_check_for_error (TLS_OUT_OF_INDEXES !=
875 (g_private_tls = TlsAlloc ()));
879 g_thread_lookup_native_funcs (void)
881 GThreadImplVtable native_vtable = { 0, };
884 kernel32 = GetModuleHandle ("KERNEL32.DLL");
886 if (kernel32 == NULL)
889 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
890 GET_FUNC(InitializeSRWLock);
891 GET_FUNC(AcquireSRWLockExclusive);
892 GET_FUNC(TryAcquireSRWLockExclusive);
893 GET_FUNC(ReleaseSRWLockExclusive);
894 GET_FUNC(AcquireSRWLockShared);
895 GET_FUNC(TryAcquireSRWLockShared);
896 GET_FUNC(ReleaseSRWLockShared);
898 GET_FUNC(InitializeConditionVariable);
899 GET_FUNC(SleepConditionVariableSRW);
900 GET_FUNC(WakeAllConditionVariable);
901 GET_FUNC(WakeConditionVariable);
904 g_thread_impl_vtable = native_vtable;
910 g_thread_DllMain (void)
912 if (g_thread_lookup_native_funcs ())
913 fprintf (stderr, "(debug) GThread using native mode\n");
916 fprintf (stderr, "(debug) GThread using Windows XP mode\n");
921 /* vim:set foldmethod=marker: */