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