remove 'joinable' parameter to backends
[platform/upstream/glib.git] / glib / gthread-win32.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gthread.c: solaris thread system implementation
5  * Copyright 1998-2001 Sebastian Wilhelmi; University of Karlsruhe
6  * Copyright 2001 Hans Breuer
7  *
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.
12  *
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.
17  *
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.
22  */
23
24 /*
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/.
29  */
30
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.
35  *
36  * As such, these functions are NOT permitted to call any other part of
37  * GLib.
38  *
39  * The thread manipulation functions (create, exit, join, etc.) have
40  * more freedom -- they can do as they please.
41  */
42
43 #include "config.h"
44
45 #include "gthread.h"
46 #include "gthreadprivate.h"
47 #include "gslice.h"
48
49 #include <windows.h>
50
51 #include <process.h>
52 #include <stdlib.h>
53 #include <stdio.h>
54
55 static void
56 g_thread_abort (gint         status,
57                 const gchar *function)
58 {
59   fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
60            strerror (status), function);
61   abort ();
62 }
63
64 /* Starting with Vista and Windows 2008, we have access to the
65  * CONDITION_VARIABLE and SRWLock primatives on Windows, which are
66  * pretty reasonable approximations of the primatives specified in
67  * POSIX 2001 (pthread_cond_t and pthread_mutex_t respectively).
68  *
69  * Both of these types are structs containing a single pointer.  That
70  * pointer is used as an atomic bitfield to support user-space mutexes
71  * that only get the kernel involved in cases of contention (similar
72  * to how futex()-based mutexes work on Linux).  The biggest advantage
73  * of these new types is that they can be statically initialised to
74  * zero.  That means that they are completely ABI compatible with our
75  * GMutex and GCond APIs.
76  *
77  * Unfortunately, Windows XP lacks these facilities and GLib still
78  * needs to support Windows XP.  Our approach here is as follows:
79  *
80  *   - avoid depending on structure declarations at compile-time by
81  *     declaring our own GMutex and GCond strutures to be
82  *     ABI-compatible with SRWLock and CONDITION_VARIABLE and using
83  *     those instead
84  *
85  *   - avoid a hard dependency on the symbols used to manipulate these
86  *     structures by doing a dynamic lookup of those symbols at
87  *     runtime
88  *
89  *   - if the symbols are not available, emulate them using other
90  *     primatives
91  *
92  * Using this approach also allows us to easily build a GLib that lacks
93  * support for Windows XP or to remove this code entirely when XP is no
94  * longer supported (end of line is currently April 8, 2014).
95  */
96 typedef struct
97 {
98   void     (__stdcall * CallThisOnThreadExit)        (void);              /* fake */
99
100   void     (__stdcall * InitializeSRWLock)           (gpointer lock);
101   void     (__stdcall * DeleteSRWLock)               (gpointer lock);     /* fake */
102   void     (__stdcall * AcquireSRWLockExclusive)     (gpointer lock);
103   BOOLEAN  (__stdcall * TryAcquireSRWLockExclusive)  (gpointer lock);
104   void     (__stdcall * ReleaseSRWLockExclusive)     (gpointer lock);
105   void     (__stdcall * AcquireSRWLockShared)        (gpointer lock);
106   BOOLEAN  (__stdcall * TryAcquireSRWLockShared)     (gpointer lock);
107   void     (__stdcall * ReleaseSRWLockShared)        (gpointer lock);
108
109   void     (__stdcall * InitializeConditionVariable) (gpointer cond);
110   void     (__stdcall * DeleteConditionVariable)     (gpointer cond);     /* fake */
111   BOOL     (__stdcall * SleepConditionVariableSRW)   (gpointer cond,
112                                                       gpointer lock,
113                                                       DWORD    timeout,
114                                                       ULONG    flags);
115   void     (__stdcall * WakeAllConditionVariable)    (gpointer cond);
116   void     (__stdcall * WakeConditionVariable)       (gpointer cond);
117 } GThreadImplVtable;
118
119 static GThreadImplVtable g_thread_impl_vtable;
120
121 /* {{{1 GMutex */
122 void
123 g_mutex_init (GMutex *mutex)
124 {
125   g_thread_impl_vtable.InitializeSRWLock (mutex);
126 }
127
128 void
129 g_mutex_clear (GMutex *mutex)
130 {
131   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
132     g_thread_impl_vtable.DeleteSRWLock (mutex);
133 }
134
135 void
136 g_mutex_lock (GMutex *mutex)
137 {
138   g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
139 }
140
141 gboolean
142 g_mutex_trylock (GMutex *mutex)
143 {
144   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
145 }
146
147 void
148 g_mutex_unlock (GMutex *mutex)
149 {
150   g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
151 }
152
153 /* {{{1 GRecMutex */
154
155 static CRITICAL_SECTION *
156 g_rec_mutex_impl_new (void)
157 {
158   CRITICAL_SECTION *cs;
159
160   cs = g_slice_new (CRITICAL_SECTION);
161   InitializeCriticalSection (cs);
162
163   return cs;
164 }
165
166 static void
167 g_rec_mutex_impl_free (CRITICAL_SECTION *cs)
168 {
169   DeleteCriticalSection (cs);
170   g_slice_free (CRITICAL_SECTION, cs);
171 }
172
173 static CRITICAL_SECTION *
174 g_rec_mutex_get_impl (GRecMutex *mutex)
175 {
176   CRITICAL_SECTION *impl = mutex->p;
177
178   if G_UNLIKELY (mutex->p == NULL)
179     {
180       impl = g_rec_mutex_impl_new ();
181       if (InterlockedCompareExchangePointer (&mutex->p, impl, NULL) != NULL)
182         g_rec_mutex_impl_free (impl);
183       impl = mutex->p;
184     }
185
186   return impl;
187 }
188
189 void
190 g_rec_mutex_init (GRecMutex *mutex)
191 {
192   mutex->p = g_rec_mutex_impl_new ();
193 }
194
195 void
196 g_rec_mutex_clear (GRecMutex *mutex)
197 {
198   g_rec_mutex_impl_free (mutex->p);
199 }
200
201 void
202 g_rec_mutex_lock (GRecMutex *mutex)
203 {
204   EnterCriticalSection (g_rec_mutex_get_impl (mutex));
205 }
206
207 void
208 g_rec_mutex_unlock (GRecMutex *mutex)
209 {
210   LeaveCriticalSection (mutex->p);
211 }
212
213 gboolean
214 g_rec_mutex_trylock (GRecMutex *mutex)
215 {
216   return TryEnterCriticalSection (g_rec_mutex_get_impl (mutex));
217 }
218
219 /* {{{1 GRWLock */
220
221 void
222 g_rw_lock_init (GRWLock *lock)
223 {
224   g_thread_impl_vtable.InitializeSRWLock (lock);
225 }
226
227 void
228 g_rw_lock_clear (GRWLock *lock)
229 {
230   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
231     g_thread_impl_vtable.DeleteSRWLock (lock);
232 }
233
234 void
235 g_rw_lock_writer_lock (GRWLock *lock)
236 {
237   g_thread_impl_vtable.AcquireSRWLockExclusive (lock);
238 }
239
240 gboolean
241 g_rw_lock_writer_trylock (GRWLock *lock)
242 {
243   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (lock);
244 }
245
246 void
247 g_rw_lock_writer_unlock (GRWLock *lock)
248 {
249   g_thread_impl_vtable.ReleaseSRWLockExclusive (lock);
250 }
251
252 void
253 g_rw_lock_reader_lock (GRWLock *lock)
254 {
255   g_thread_impl_vtable.AcquireSRWLockShared (lock);
256 }
257
258 gboolean
259 g_rw_lock_reader_trylock (GRWLock *lock)
260 {
261   return g_thread_impl_vtable.TryAcquireSRWLockShared (lock);
262 }
263
264 void
265 g_rw_lock_reader_unlock (GRWLock *lock)
266 {
267   g_thread_impl_vtable.ReleaseSRWLockShared (lock);
268 }
269
270 /* {{{1 GCond */
271 void
272 g_cond_init (GCond *cond)
273 {
274   g_thread_impl_vtable.InitializeConditionVariable (cond);
275 }
276
277 void
278 g_cond_clear (GCond *cond)
279 {
280   if (g_thread_impl_vtable.DeleteConditionVariable)
281     g_thread_impl_vtable.DeleteConditionVariable (cond);
282 }
283
284 void
285 g_cond_signal (GCond *cond)
286 {
287   g_thread_impl_vtable.WakeConditionVariable (cond);
288 }
289
290 void
291 g_cond_broadcast (GCond *cond)
292 {
293   g_thread_impl_vtable.WakeAllConditionVariable (cond);
294 }
295
296 void
297 g_cond_wait (GCond  *cond,
298              GMutex *entered_mutex)
299 {
300   g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
301 }
302
303 gboolean
304 g_cond_timedwait (GCond  *cond,
305                   GMutex *entered_mutex,
306                   gint64  abs_time)
307 {
308   gint64 span;
309   FILETIME ft;
310   gint64 now;
311
312   GetSystemTimeAsFileTime (&ft);
313   memmove (&now, &ft, sizeof (FILETIME));
314
315   now -= G_GINT64_CONSTANT (116444736000000000);
316   now /= 10;
317
318   span = abs_time - now;
319
320   if G_UNLIKELY (span < 0)
321     span = 0;
322
323   if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
324     span = INFINITE;
325
326   return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
327 }
328
329 gboolean
330 g_cond_timed_wait (GCond    *cond,
331                    GMutex   *entered_mutex,
332                    GTimeVal *abs_time)
333 {
334   if (abs_time)
335     {
336       gint64 micros;
337
338       micros = abs_time->tv_sec;
339       micros *= 1000000;
340       micros += abs_time->tv_usec;
341
342       return g_cond_timedwait (cond, entered_mutex, micros);
343     }
344   else
345     {
346       g_cond_wait (cond, entered_mutex);
347       return TRUE;
348     }
349 }
350
351 /* {{{1 GPrivate */
352
353 typedef struct _GPrivateDestructor GPrivateDestructor;
354
355 struct _GPrivateDestructor
356 {
357   DWORD               index;
358   GDestroyNotify      notify;
359   GPrivateDestructor *next;
360 };
361
362 static GPrivateDestructor * volatile g_private_destructors;
363 static CRITICAL_SECTION g_private_lock;
364
365 static DWORD
366 g_private_get_impl (GPrivate *key)
367 {
368   DWORD impl = (DWORD) key->p;
369
370   if G_UNLIKELY (impl == 0)
371     {
372       EnterCriticalSection (&g_private_lock);
373       impl = (DWORD) key->p;
374       if (impl == 0)
375         {
376           GPrivateDestructor *destructor;
377
378           impl = TlsAlloc ();
379
380           if (impl == TLS_OUT_OF_INDEXES)
381             g_thread_abort (0, "TlsAlloc");
382
383           if (key->notify != NULL)
384             {
385               destructor = malloc (sizeof (GPrivateDestructor));
386               if G_UNLIKELY (destructor == NULL)
387                 g_thread_abort (errno, "malloc");
388               destructor->index = impl;
389               destructor->notify = key->notify;
390               destructor->next = g_private_destructors;
391
392               /* We need to do an atomic store due to the unlocked
393                * access to the destructor list from the thread exit
394                * function.
395                *
396                * It can double as a sanity check...
397                */
398               if (InterlockedCompareExchangePointer (&g_private_destructors, destructor,
399                                                      destructor->next) != destructor->next)
400                 g_thread_abort (0, "g_private_get_impl(1)");
401             }
402
403           /* Ditto, due to the unlocked access on the fast path */
404           if (InterlockedCompareExchangePointer (&key->p, impl, NULL) != NULL)
405             g_thread_abort (0, "g_private_get_impl(2)");
406         }
407       LeaveCriticalSection (&g_private_lock);
408     }
409
410   return impl;
411 }
412
413 gpointer
414 g_private_get (GPrivate *key)
415 {
416   return TlsGetValue (g_private_get_impl (key));
417 }
418
419 void
420 g_private_set (GPrivate *key,
421                gpointer  value)
422 {
423   TlsSetValue (g_private_get_impl (key), value);
424 }
425
426 void
427 g_private_replace (GPrivate *key,
428                    gpointer  value)
429 {
430   DWORD impl = g_private_get_impl (key);
431   gpointer old;
432
433   old = TlsGetValue (impl);
434   if (old && key->notify)
435     key->notify (old);
436   TlsSetValue (impl, value);
437 }
438
439 /* {{{1 GThread */
440
441 #include "glib.h"
442 #include "gthreadprivate.h"
443
444 #define win32_check_for_error(what) G_STMT_START{                       \
445   if (!(what))                                                          \
446     g_error ("file %s: line %d (%s): error %s during %s",               \
447              __FILE__, __LINE__, G_STRFUNC,                             \
448              g_win32_error_message (GetLastError ()), #what);           \
449   }G_STMT_END
450
451 #define G_MUTEX_SIZE (sizeof (gpointer))
452
453 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
454
455 typedef struct
456 {
457   GRealThread thread;
458
459   GThreadFunc proxy;
460   HANDLE      handle;
461 } GThreadWin32;
462
463 void
464 g_system_thread_free (GRealThread *thread)
465 {
466   GThreadWin32 *wt = (GThreadWin32 *) thread;
467
468   win32_check_for_error (CloseHandle (wt->handle));
469   g_slice_free (GThreadWin32, wt);
470 }
471
472 void
473 g_system_thread_exit (void)
474 {
475   _endthreadex (0);
476 }
477
478 static guint __stdcall
479 g_thread_win32_proxy (gpointer data)
480 {
481   GThreadWin32 *self = data;
482
483   self->proxy (self);
484
485   g_system_thread_exit ();
486
487   g_assert_not_reached ();
488
489   return 0;
490 }
491
492 GRealThread *
493 g_system_thread_new (GThreadFunc   func,
494                      gulong        stack_size,
495                      GError      **error)
496 {
497   GThreadWin32 *thread;
498   guint ignore;
499
500   thread = g_slice_new0 (GThreadWin32);
501   thread->proxy = func;
502
503   thread->handle = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_win32_proxy, thread, 0, &ignore);
504
505   if (thread->handle == NULL)
506     {
507       gchar *win_error = g_win32_error_message (GetLastError ());
508       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
509                    "Error creating thread: %s", win_error);
510       g_free (win_error);
511       g_slice_free (GThreadWin32, thread);
512       return NULL;
513     }
514
515   return (GRealThread *) thread;
516 }
517
518 void
519 g_thread_yield (void)
520 {
521   Sleep(0);
522 }
523
524 void
525 g_system_thread_wait (GRealThread *thread)
526 {
527   GThreadWin32 *wt = (GThreadWin32 *) thread;
528
529   win32_check_for_error (WAIT_FAILED != WaitForSingleObject (wt->handle, INFINITE));
530 }
531
532 void
533 g_system_thread_set_name (const gchar *name)
534 {
535   /* FIXME: implement */
536 }
537
538 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
539
540 static CRITICAL_SECTION g_thread_xp_lock;
541 static DWORD            g_thread_xp_waiter_tls;
542
543 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
544 typedef struct _GThreadXpWaiter GThreadXpWaiter;
545 struct _GThreadXpWaiter
546 {
547   HANDLE                    event;
548   volatile GThreadXpWaiter *next;
549 };
550
551 static GThreadXpWaiter *
552 g_thread_xp_waiter_get (void)
553 {
554   GThreadXpWaiter *waiter;
555
556   waiter = TlsGetValue (g_thread_xp_waiter_tls);
557
558   if G_UNLIKELY (waiter == NULL)
559     {
560       waiter = malloc (sizeof (GThreadXpWaiter));
561       if (waiter == NULL)
562         g_thread_abort (GetLastError (), "malloc");
563       waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
564       if (waiter->event == NULL)
565         g_thread_abort (GetLastError (), "CreateEvent");
566
567       TlsSetValue (g_thread_xp_waiter_tls, waiter);
568     }
569
570   return waiter;
571 }
572
573 static void __stdcall
574 g_thread_xp_CallThisOnThreadExit (void)
575 {
576   GThreadXpWaiter *waiter;
577
578   waiter = TlsGetValue (g_thread_xp_waiter_tls);
579
580   if (waiter != NULL)
581     {
582       TlsSetValue (g_thread_xp_waiter_tls, NULL);
583       CloseHandle (waiter->event);
584       free (waiter);
585     }
586 }
587
588 /* {{{2 SRWLock emulation */
589 typedef struct
590 {
591   CRITICAL_SECTION  writer_lock;
592   gboolean          ever_shared;    /* protected by writer_lock */
593   gboolean          writer_locked;  /* protected by writer_lock */
594
595   /* below is only ever touched if ever_shared becomes true */
596   CRITICAL_SECTION  atomicity;
597   GThreadXpWaiter  *queued_writer; /* protected by atomicity lock */
598   gint              num_readers;   /* protected by atomicity lock */
599 } GThreadSRWLock;
600
601 static void __stdcall
602 g_thread_xp_InitializeSRWLock (gpointer mutex)
603 {
604   *(GThreadSRWLock * volatile *) mutex = NULL;
605 }
606
607 static void __stdcall
608 g_thread_xp_DeleteSRWLock (gpointer mutex)
609 {
610   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
611
612   if (lock)
613     {
614       if (lock->ever_shared)
615         DeleteCriticalSection (&lock->atomicity);
616
617       DeleteCriticalSection (&lock->writer_lock);
618       free (lock);
619     }
620 }
621
622 static GThreadSRWLock * __stdcall
623 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
624 {
625   GThreadSRWLock *result;
626
627   /* It looks like we're missing some barriers here, but this code only
628    * ever runs on Windows XP, which in turn only ever runs on hardware
629    * with a relatively rigid memory model.  The 'volatile' will take
630    * care of the compiler.
631    */
632   result = *lock;
633
634   if G_UNLIKELY (result == NULL)
635     {
636       EnterCriticalSection (&g_thread_xp_lock);
637
638       result = malloc (sizeof (GThreadSRWLock));
639
640       if (result == NULL)
641         g_thread_abort (errno, "malloc");
642
643       InitializeCriticalSection (&result->writer_lock);
644       result->writer_locked = FALSE;
645       result->ever_shared = FALSE;
646       *lock = result;
647
648       LeaveCriticalSection (&g_thread_xp_lock);
649     }
650
651   return result;
652 }
653
654 static void __stdcall
655 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
656 {
657   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
658
659   EnterCriticalSection (&lock->writer_lock);
660
661   /* CRITICAL_SECTION is reentrant, but SRWLock is not.
662    * Detect the deadlock that would occur on later Windows version.
663    */
664   g_assert (!lock->writer_locked);
665   lock->writer_locked = TRUE;
666
667   if (lock->ever_shared)
668     {
669       GThreadXpWaiter *waiter = NULL;
670
671       EnterCriticalSection (&lock->atomicity);
672       if (lock->num_readers > 0)
673         lock->queued_writer = waiter = g_thread_xp_waiter_get ();
674       LeaveCriticalSection (&lock->atomicity);
675
676       if (waiter != NULL)
677         WaitForSingleObject (waiter->event, INFINITE);
678
679       lock->queued_writer = NULL;
680     }
681 }
682
683 static BOOLEAN __stdcall
684 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
685 {
686   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
687
688   if (!TryEnterCriticalSection (&lock->writer_lock))
689     return FALSE;
690
691   /* CRITICAL_SECTION is reentrant, but SRWLock is not.
692    * Ensure that this properly returns FALSE (as SRWLock would).
693    */
694   if G_UNLIKELY (lock->writer_locked)
695     {
696       LeaveCriticalSection (&lock->writer_lock);
697       return FALSE;
698     }
699
700   lock->writer_locked = TRUE;
701
702   if (lock->ever_shared)
703     {
704       gboolean available;
705
706       EnterCriticalSection (&lock->atomicity);
707       available = lock->num_readers == 0;
708       LeaveCriticalSection (&lock->atomicity);
709
710       if (!available)
711         {
712           LeaveCriticalSection (&lock->writer_lock);
713           return FALSE;
714         }
715     }
716
717   return TRUE;
718 }
719
720 static void __stdcall
721 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
722 {
723   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
724
725   lock->writer_locked = FALSE;
726
727   /* We need this until we fix some weird parts of GLib that try to
728    * unlock freshly-allocated mutexes.
729    */
730   if (lock != NULL)
731     LeaveCriticalSection (&lock->writer_lock);
732 }
733
734 static void
735 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
736 {
737   if G_UNLIKELY (!lock->ever_shared)
738     {
739       InitializeCriticalSection (&lock->atomicity);
740       lock->queued_writer = NULL;
741       lock->num_readers = 0;
742
743       lock->ever_shared = TRUE;
744     }
745
746   EnterCriticalSection (&lock->atomicity);
747   lock->num_readers++;
748   LeaveCriticalSection (&lock->atomicity);
749 }
750
751 static void __stdcall
752 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
753 {
754   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
755
756   EnterCriticalSection (&lock->writer_lock);
757
758   /* See g_thread_xp_AcquireSRWLockExclusive */
759   g_assert (!lock->writer_locked);
760
761   g_thread_xp_srwlock_become_reader (lock);
762
763   LeaveCriticalSection (&lock->writer_lock);
764 }
765
766 static BOOLEAN __stdcall
767 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
768 {
769   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
770
771   if (!TryEnterCriticalSection (&lock->writer_lock))
772     return FALSE;
773
774   /* See g_thread_xp_AcquireSRWLockExclusive */
775   if G_UNLIKELY (lock->writer_locked)
776     {
777       LeaveCriticalSection (&lock->writer_lock);
778       return FALSE;
779     }
780
781   g_thread_xp_srwlock_become_reader (lock);
782
783   LeaveCriticalSection (&lock->writer_lock);
784
785   return TRUE;
786 }
787
788 static void __stdcall
789 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
790 {
791   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
792
793   EnterCriticalSection (&lock->atomicity);
794
795   lock->num_readers--;
796
797   if (lock->num_readers == 0 && lock->queued_writer)
798     SetEvent (lock->queued_writer->event);
799
800   LeaveCriticalSection (&lock->atomicity);
801 }
802
803 /* {{{2 CONDITION_VARIABLE emulation */
804 typedef struct
805 {
806   volatile GThreadXpWaiter  *first;
807   volatile GThreadXpWaiter **last_ptr;
808 } GThreadXpCONDITION_VARIABLE;
809
810 static void __stdcall
811 g_thread_xp_InitializeConditionVariable (gpointer cond)
812 {
813   *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
814 }
815
816 static void __stdcall
817 g_thread_xp_DeleteConditionVariable (gpointer cond)
818 {
819   GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
820
821   if (cv)
822     free (cv);
823 }
824
825 static GThreadXpCONDITION_VARIABLE * __stdcall
826 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
827 {
828   GThreadXpCONDITION_VARIABLE *result;
829
830   /* It looks like we're missing some barriers here, but this code only
831    * ever runs on Windows XP, which in turn only ever runs on hardware
832    * with a relatively rigid memory model.  The 'volatile' will take
833    * care of the compiler.
834    */
835   result = *cond;
836
837   if G_UNLIKELY (result == NULL)
838     {
839       result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
840
841       if (result == NULL)
842         g_thread_abort (errno, "malloc");
843
844       result->first = NULL;
845       result->last_ptr = &result->first;
846
847       if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
848         {
849           free (result);
850           result = *cond;
851         }
852     }
853
854   return result;
855 }
856
857 static BOOL __stdcall
858 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
859                                        gpointer mutex,
860                                        DWORD    timeout,
861                                        ULONG    flags)
862 {
863   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
864   GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
865   DWORD status;
866
867   waiter->next = NULL;
868
869   EnterCriticalSection (&g_thread_xp_lock);
870   *cv->last_ptr = waiter;
871   cv->last_ptr = &waiter->next;
872   LeaveCriticalSection (&g_thread_xp_lock);
873
874   g_mutex_unlock (mutex);
875   status = WaitForSingleObject (waiter->event, timeout);
876
877   if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
878     g_thread_abort (GetLastError (), "WaitForSingleObject");
879
880   g_mutex_lock (mutex);
881
882   return status == WAIT_OBJECT_0;
883 }
884
885 static void __stdcall
886 g_thread_xp_WakeConditionVariable (gpointer cond)
887 {
888   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
889   volatile GThreadXpWaiter *waiter;
890
891   EnterCriticalSection (&g_thread_xp_lock);
892   waiter = cv->first;
893   if (waiter != NULL)
894     {
895       cv->first = waiter->next;
896       if (cv->first == NULL)
897         cv->last_ptr = &cv->first;
898     }
899   LeaveCriticalSection (&g_thread_xp_lock);
900
901   if (waiter != NULL)
902     SetEvent (waiter->event);
903 }
904
905 static void __stdcall
906 g_thread_xp_WakeAllConditionVariable (gpointer cond)
907 {
908   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
909   volatile GThreadXpWaiter *waiter;
910
911   EnterCriticalSection (&g_thread_xp_lock);
912   waiter = cv->first;
913   cv->first = NULL;
914   cv->last_ptr = &cv->first;
915   LeaveCriticalSection (&g_thread_xp_lock);
916
917   while (waiter != NULL)
918     {
919       volatile GThreadXpWaiter *next;
920
921       next = waiter->next;
922       SetEvent (waiter->event);
923       waiter = next;
924     }
925 }
926
927 /* {{{2 XP Setup */
928 static void
929 g_thread_xp_init (void)
930 {
931   static const GThreadImplVtable g_thread_xp_impl_vtable = {
932     g_thread_xp_CallThisOnThreadExit,
933     g_thread_xp_InitializeSRWLock,
934     g_thread_xp_DeleteSRWLock,
935     g_thread_xp_AcquireSRWLockExclusive,
936     g_thread_xp_TryAcquireSRWLockExclusive,
937     g_thread_xp_ReleaseSRWLockExclusive,
938     g_thread_xp_AcquireSRWLockShared,
939     g_thread_xp_TryAcquireSRWLockShared,
940     g_thread_xp_ReleaseSRWLockShared,
941     g_thread_xp_InitializeConditionVariable,
942     g_thread_xp_DeleteConditionVariable,
943     g_thread_xp_SleepConditionVariableSRW,
944     g_thread_xp_WakeAllConditionVariable,
945     g_thread_xp_WakeConditionVariable
946   };
947
948   InitializeCriticalSection (&g_thread_xp_lock);
949   g_thread_xp_waiter_tls = TlsAlloc ();
950
951   g_thread_impl_vtable = g_thread_xp_impl_vtable;
952 }
953
954 /* {{{1 Epilogue */
955
956 static gboolean
957 g_thread_lookup_native_funcs (void)
958 {
959   GThreadImplVtable native_vtable = { 0, };
960   HMODULE kernel32;
961
962   kernel32 = GetModuleHandle ("KERNEL32.DLL");
963
964   if (kernel32 == NULL)
965     return FALSE;
966
967 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
968   GET_FUNC(InitializeSRWLock);
969   GET_FUNC(AcquireSRWLockExclusive);
970   GET_FUNC(TryAcquireSRWLockExclusive);
971   GET_FUNC(ReleaseSRWLockExclusive);
972   GET_FUNC(AcquireSRWLockShared);
973   GET_FUNC(TryAcquireSRWLockShared);
974   GET_FUNC(ReleaseSRWLockShared);
975
976   GET_FUNC(InitializeConditionVariable);
977   GET_FUNC(SleepConditionVariableSRW);
978   GET_FUNC(WakeAllConditionVariable);
979   GET_FUNC(WakeConditionVariable);
980 #undef GET_FUNC
981
982   g_thread_impl_vtable = native_vtable;
983
984   return TRUE;
985 }
986
987 G_GNUC_INTERNAL void
988 g_thread_win32_init (void)
989 {
990   if (g_thread_lookup_native_funcs ())
991     fprintf (stderr, "(debug) GThread using native mode\n");
992   else
993     {
994       fprintf (stderr, "(debug) GThread using Windows XP mode\n");
995       g_thread_xp_init ();
996     }
997
998   InitializeCriticalSection (&g_private_lock);
999 }
1000
1001 G_GNUC_INTERNAL void
1002 g_thread_win32_thread_detach (void)
1003 {
1004   gboolean dtors_called;
1005
1006   do
1007     {
1008       GPrivateDestructor *dtor;
1009
1010       /* We go by the POSIX book on this one.
1011        *
1012        * If we call a destructor then there is a chance that some new
1013        * TLS variables got set by code called in that destructor.
1014        *
1015        * Loop until nothing is left.
1016        */
1017       dtors_called = FALSE;
1018
1019       for (dtor = g_private_destructors; dtor; dtor = dtor->next)
1020         {
1021           gpointer value;
1022
1023           value = TlsGetValue (dtor->index);
1024           if (value != NULL && dtor->notify != NULL)
1025             {
1026               /* POSIX says to clear this before the call */
1027               TlsSetValue (dtor->index, NULL);
1028               dtor->notify (value);
1029               dtors_called = TRUE;
1030             }
1031         }
1032     }
1033   while (dtors_called);
1034
1035   if (g_thread_impl_vtable.CallThisOnThreadExit)
1036     g_thread_impl_vtable.CallThisOnThreadExit ();
1037 }
1038
1039 /* vim:set foldmethod=marker: */