win32: Add 'shared' support to SRWLock emulation
[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
48 #include <windows.h>
49
50 #include <process.h>
51 #include <stdlib.h>
52 #include <stdio.h>
53
54 static void
55 g_thread_abort (gint         status,
56                 const gchar *function)
57 {
58   fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
59            strerror (status), function);
60   abort ();
61 }
62
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).
67  *
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:
74  *
75  *   GMutex mutex = G_MUTEX_INIT;
76  *
77  * and
78  *
79  *   GCond cond = G_COND_INIT;
80  *
81  * Unfortunately, Windows XP lacks these facilities and GLib still
82  * needs to support Windows XP.  Our approach here is as follows:
83  *
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
87  *     those instead
88  *
89  *   - avoid a hard dependency on the symbols used to manipulate these
90  *     structures by doing a dynamic lookup of those symbols at
91  *     runtime
92  *
93  *   - if the symbols are not available, emulate them using other
94  *     primatives
95  *
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).
99  */
100 typedef struct
101 {
102   void     (__stdcall * CallThisOnThreadExit)        (void);              /* fake */
103
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);
112
113   void     (__stdcall * InitializeConditionVariable) (gpointer cond);
114   void     (__stdcall * DeleteConditionVariable)     (gpointer cond);     /* fake */
115   BOOL     (__stdcall * SleepConditionVariableSRW)   (gpointer cond,
116                                                       gpointer lock,
117                                                       DWORD    timeout,
118                                                       ULONG    flags);
119   void     (__stdcall * WakeAllConditionVariable)    (gpointer cond);
120   void     (__stdcall * WakeConditionVariable)       (gpointer cond);
121 } GThreadImplVtable;
122
123 static GThreadImplVtable g_thread_impl_vtable;
124
125 /* {{{1 GMutex */
126 void
127 g_mutex_init (GMutex *mutex)
128 {
129   g_thread_impl_vtable.InitializeSRWLock (mutex);
130 }
131
132 void
133 g_mutex_clear (GMutex *mutex)
134 {
135   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
136     g_thread_impl_vtable.DeleteSRWLock (mutex);
137 }
138
139 void
140 g_mutex_lock (GMutex *mutex)
141 {
142   g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
143 }
144
145 gboolean
146 g_mutex_trylock (GMutex *mutex)
147 {
148   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
149 }
150
151 void
152 g_mutex_unlock (GMutex *mutex)
153 {
154   g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
155 }
156
157 /* {{{1 GCond */
158 void
159 g_cond_init (GCond *cond)
160 {
161   g_thread_impl_vtable.InitializeConditionVariable (cond);
162 }
163
164 void
165 g_cond_clear (GCond *cond)
166 {
167   if (g_thread_impl_vtable.DeleteConditionVariable)
168     g_thread_impl_vtable.DeleteConditionVariable (cond);
169 }
170
171 void
172 g_cond_signal (GCond *cond)
173 {
174   g_thread_impl_vtable.WakeConditionVariable (cond);
175 }
176
177 void
178 g_cond_broadcast (GCond *cond)
179 {
180   g_thread_impl_vtable.WakeAllConditionVariable (cond);
181 }
182
183 void
184 g_cond_wait (GCond  *cond,
185              GMutex *entered_mutex)
186 {
187   g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
188 }
189
190 gboolean
191 g_cond_timedwait (GCond  *cond,
192                   GMutex *entered_mutex,
193                   gint64  abs_time)
194 {
195   gint64 span;
196   FILETIME ft;
197   gint64 now;
198
199   GetSystemTimeAsFileTime (&ft);
200   memmove (&now, &ft, sizeof (FILETIME));
201
202   now -= G_GINT64_CONSTANT (116444736000000000);
203   now /= 10;
204
205   span = abs_time - now;
206
207   if G_UNLIKELY (span < 0)
208     span = 0;
209
210   if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
211     span = INFINITE;
212
213   return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
214 }
215
216 gboolean
217 g_cond_timed_wait (GCond    *cond,
218                    GMutex   *entered_mutex,
219                    GTimeVal *abs_time)
220 {
221   if (abs_time)
222     {
223       gint64 micros;
224
225       micros = abs_time->tv_sec;
226       micros *= 1000000;
227       micros += abs_time->tv_usec;
228
229       return g_cond_timedwait (cond, entered_mutex, micros);
230     }
231   else
232     {
233       g_cond_wait (cond, entered_mutex);
234       return TRUE;
235     }
236 }
237
238 /* {{{1 GPrivate */
239
240 typedef struct _GPrivateDestructor GPrivateDestructor;
241
242 struct _GPrivateDestructor
243 {
244   DWORD               index;
245   GDestroyNotify      notify;
246   GPrivateDestructor *next;
247 };
248
249 static GPrivateDestructor * volatile g_private_destructors;
250
251 void
252 g_private_init (GPrivate       *key,
253                 GDestroyNotify  notify)
254 {
255   GPrivateDestructor *destructor;
256
257   key->index = TlsAlloc ();
258
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;
264
265   do
266     destructor->next = g_private_destructors;
267   while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
268
269   key->ready = TRUE;
270 }
271
272 gpointer
273 g_private_get (GPrivate *key)
274 {
275   if (!key->ready)
276     return key->single_value;
277
278   return TlsGetValue (key->index);
279 }
280
281 void
282 g_private_set (GPrivate *key,
283                gpointer  value)
284 {
285   if (!key->ready)
286     {
287       key->single_value = value;
288       return;
289     }
290
291   TlsSetValue (key->index, value);
292 }
293
294 /* {{{1 GThread */
295
296 #include "glib.h"
297 #include "gthreadprivate.h"
298
299 #define win32_check_for_error(what) G_STMT_START{                       \
300   if (!(what))                                                          \
301     g_error ("file %s: line %d (%s): error %s during %s",               \
302              __FILE__, __LINE__, G_STRFUNC,                             \
303              g_win32_error_message (GetLastError ()), #what);           \
304   }G_STMT_END
305
306 #define G_MUTEX_SIZE (sizeof (gpointer))
307
308 static DWORD g_thread_self_tls;
309 static DWORD g_private_tls;
310
311 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
312
313 typedef struct _GThreadData GThreadData;
314 struct _GThreadData
315 {
316   GThreadFunc func;
317   gpointer data;
318   HANDLE thread;
319   gboolean joinable;
320 };
321
322 void
323 g_system_thread_self (gpointer thread)
324 {
325   GThreadData *self = TlsGetValue (g_thread_self_tls);
326
327   if (!self)
328     {
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));
337       self->func = NULL;
338       self->data = NULL;
339       self->joinable = FALSE;
340     }
341
342   *(GThreadData **)thread = self;
343 }
344
345 void
346 g_system_thread_exit (void)
347 {
348   GThreadData *self = TlsGetValue (g_thread_self_tls);
349   gboolean dtors_called;
350
351   do
352     {
353       GPrivateDestructor *dtor;
354
355       /* We go by the POSIX book on this one.
356        *
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.
359        *
360        * Loop until nothing is left.
361        */
362       dtors_called = FALSE;
363
364       for (dtor = g_private_destructors; dtor; dtor = dtor->next)
365         {
366           gpointer value;
367
368           value = TlsGetValue (dtor->index);
369           if (value != NULL && dtor->notify != NULL)
370             {
371               /* POSIX says to clear this before the call */
372               TlsSetValue (dtor->index, NULL);
373               dtor->notify (value);
374               dtors_called = TRUE;
375             }
376         }
377     }
378   while (dtors_called);
379
380   if (self)
381     {
382       if (!self->joinable)
383         {
384           win32_check_for_error (CloseHandle (self->thread));
385           g_free (self);
386         }
387       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
388     }
389
390   if (g_thread_impl_vtable.CallThisOnThreadExit)
391     g_thread_impl_vtable.CallThisOnThreadExit ();
392
393   _endthreadex (0);
394 }
395
396 static guint __stdcall
397 g_thread_proxy (gpointer data)
398 {
399   GThreadData *self = (GThreadData*) data;
400
401   win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
402
403   self->func (self->data);
404
405   g_system_thread_exit ();
406
407   g_assert_not_reached ();
408
409   return 0;
410 }
411
412 void
413 g_system_thread_create (GThreadFunc       func,
414                         gpointer          data,
415                         gulong            stack_size,
416                         gboolean          joinable,
417                         gpointer          thread,
418                         GError          **error)
419 {
420   guint ignore;
421   GThreadData *retval;
422
423   g_return_if_fail (func);
424
425   retval = g_new(GThreadData, 1);
426   retval->func = func;
427   retval->data = data;
428
429   retval->joinable = joinable;
430
431   retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
432                                             retval, 0, &ignore);
433
434   if (retval->thread == NULL)
435     {
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);
439       g_free (retval);
440       g_free (win_error);
441       return;
442     }
443
444   *(GThreadData **)thread = retval;
445 }
446
447 void
448 g_thread_yield (void)
449 {
450   Sleep(0);
451 }
452
453 void
454 g_system_thread_join (gpointer thread)
455 {
456   GThreadData *target = *(GThreadData **)thread;
457
458   g_return_if_fail (target->joinable);
459
460   win32_check_for_error (WAIT_FAILED !=
461                          WaitForSingleObject (target->thread, INFINITE));
462
463   win32_check_for_error (CloseHandle (target->thread));
464   g_free (target);
465 }
466
467 gboolean
468 g_system_thread_equal (gpointer thread1,
469                        gpointer thread2)
470 {
471    return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
472 }
473
474 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
475
476 static CRITICAL_SECTION g_thread_xp_lock;
477 static DWORD            g_thread_xp_waiter_tls;
478
479 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
480 typedef struct _GThreadXpWaiter GThreadXpWaiter;
481 struct _GThreadXpWaiter
482 {
483   HANDLE                    event;
484   volatile GThreadXpWaiter *next;
485 };
486
487 static GThreadXpWaiter *
488 g_thread_xp_waiter_get (void)
489 {
490   GThreadXpWaiter *waiter;
491
492   waiter = TlsGetValue (g_thread_xp_waiter_tls);
493
494   if G_UNLIKELY (waiter == NULL)
495     {
496       waiter = malloc (sizeof (GThreadXpWaiter));
497       if (waiter == NULL)
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");
502
503       TlsSetValue (g_thread_xp_waiter_tls, waiter);
504     }
505
506   return waiter;
507 }
508
509 static void __stdcall
510 g_thread_xp_CallThisOnThreadExit (void)
511 {
512   GThreadXpWaiter *waiter;
513
514   waiter = TlsGetValue (g_thread_xp_waiter_tls);
515
516   if (waiter != NULL)
517     {
518       TlsSetValue (g_thread_xp_waiter_tls, NULL);
519       CloseHandle (waiter->event);
520       free (waiter);
521     }
522 }
523
524 /* {{{2 SRWLock emulation */
525 typedef struct
526 {
527   CRITICAL_SECTION  writer_lock;
528   gboolean          ever_shared;    /* protected by writer_lock */
529
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 */
534 } GThreadSRWLock;
535
536 static void __stdcall
537 g_thread_xp_InitializeSRWLock (gpointer mutex)
538 {
539   *(GThreadSRWLock * volatile *) mutex = NULL;
540 }
541
542 static void __stdcall
543 g_thread_xp_DeleteSRWLock (gpointer mutex)
544 {
545   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
546
547   if (lock)
548     {
549       if (lock->ever_shared)
550         DeleteCriticalSection (&lock->atomicity);
551
552       DeleteCriticalSection (&lock->writer_lock);
553       free (lock);
554     }
555 }
556
557 static GThreadSRWLock * __stdcall
558 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
559 {
560   GThreadSRWLock *result;
561
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.
566    */
567   result = *lock;
568
569   if G_UNLIKELY (result == NULL)
570     {
571       EnterCriticalSection (&g_thread_xp_lock);
572
573       result = malloc (sizeof (GThreadSRWLock));
574
575       if (result == NULL)
576         g_thread_abort (errno, "malloc");
577
578       InitializeCriticalSection (&result->writer_lock);
579       result->ever_shared = FALSE;
580       *lock = result;
581
582       LeaveCriticalSection (&g_thread_xp_lock);
583     }
584
585   return result;
586 }
587
588 static void __stdcall
589 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
590 {
591   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
592
593   EnterCriticalSection (&lock->writer_lock);
594
595   if (lock->ever_shared)
596     {
597       GThreadXpWaiter *waiter = NULL;
598
599       EnterCriticalSection (&lock->atomicity);
600       if (lock->num_readers > 0)
601         lock->queued_writer = waiter = g_thread_xp_waiter_get ();
602       LeaveCriticalSection (&lock->atomicity);
603
604       if (waiter != NULL)
605         WaitForSingleObject (waiter->event, INFINITE);
606
607       lock->queued_writer = NULL;
608     }
609 }
610
611 static BOOLEAN __stdcall
612 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
613 {
614   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
615
616   if (!TryEnterCriticalSection (&lock->writer_lock))
617     return FALSE;
618
619   if (lock->ever_shared)
620     {
621       gboolean available;
622
623       EnterCriticalSection (&lock->atomicity);
624       available = lock->num_readers == 0;
625       LeaveCriticalSection (&lock->atomicity);
626
627       if (!available)
628         {
629           LeaveCriticalSection (&lock->writer_lock);
630           return FALSE;
631         }
632     }
633
634   return TRUE;
635 }
636
637 static void __stdcall
638 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
639 {
640   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
641
642   /* We need this until we fix some weird parts of GLib that try to
643    * unlock freshly-allocated mutexes.
644    */
645   if (lock != NULL)
646     LeaveCriticalSection (&lock->writer_lock);
647 }
648
649 static void
650 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
651 {
652   if G_UNLIKELY (!lock->ever_shared)
653     {
654       InitializeCriticalSection (&lock->atomicity);
655       lock->queued_writer = NULL;
656       lock->num_readers = 0;
657
658       lock->ever_shared = TRUE;
659     }
660
661   EnterCriticalSection (&lock->atomicity);
662   lock->num_readers++;
663   LeaveCriticalSection (&lock->atomicity);
664 }
665
666 static void __stdcall
667 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
668 {
669   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
670
671   EnterCriticalSection (&lock->writer_lock);
672
673   g_thread_xp_srwlock_become_reader (lock);
674
675   LeaveCriticalSection (&lock->writer_lock);
676 }
677
678 static BOOLEAN __stdcall
679 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
680 {
681   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
682
683   if (!TryEnterCriticalSection (&lock->writer_lock))
684     return FALSE;
685
686   g_thread_xp_srwlock_become_reader (lock);
687
688   LeaveCriticalSection (&lock->writer_lock);
689
690   return TRUE;
691 }
692
693 static void __stdcall
694 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
695 {
696   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
697
698   EnterCriticalSection (&lock->atomicity);
699
700   lock->num_readers--;
701
702   if (lock->num_readers == 0 && lock->queued_writer)
703     SetEvent (lock->queued_writer->event);
704
705   LeaveCriticalSection (&lock->atomicity);
706 }
707
708 /* {{{2 CONDITION_VARIABLE emulation */
709 typedef struct
710 {
711   volatile GThreadXpWaiter  *first;
712   volatile GThreadXpWaiter **last_ptr;
713 } GThreadXpCONDITION_VARIABLE;
714
715 static void __stdcall
716 g_thread_xp_InitializeConditionVariable (gpointer cond)
717 {
718   *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
719 }
720
721 static void __stdcall
722 g_thread_xp_DeleteConditionVariable (gpointer cond)
723 {
724   GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
725
726   if (cv)
727     free (cv);
728 }
729
730 static GThreadXpCONDITION_VARIABLE * __stdcall
731 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
732 {
733   GThreadXpCONDITION_VARIABLE *result;
734
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.
739    */
740   result = *cond;
741
742   if G_UNLIKELY (result == NULL)
743     {
744       result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
745
746       if (result == NULL)
747         g_thread_abort (errno, "malloc");
748
749       result->first = NULL;
750       result->last_ptr = &result->first;
751
752       if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
753         {
754           free (result);
755           result = *cond;
756         }
757     }
758
759   return result;
760 }
761
762 static BOOL __stdcall
763 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
764                                        gpointer mutex,
765                                        DWORD    timeout,
766                                        ULONG    flags)
767 {
768   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
769   GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
770   DWORD status;
771
772   waiter->next = NULL;
773
774   EnterCriticalSection (&g_thread_xp_lock);
775   *cv->last_ptr = waiter;
776   cv->last_ptr = &waiter->next;
777   LeaveCriticalSection (&g_thread_xp_lock);
778
779   g_mutex_unlock (mutex);
780   status = WaitForSingleObject (waiter->event, timeout);
781
782   if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
783     g_thread_abort (GetLastError (), "WaitForSingleObject");
784
785   g_mutex_lock (mutex);
786
787   return status == WAIT_OBJECT_0;
788 }
789
790 static void __stdcall
791 g_thread_xp_WakeConditionVariable (gpointer cond)
792 {
793   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
794   volatile GThreadXpWaiter *waiter;
795
796   EnterCriticalSection (&g_thread_xp_lock);
797   waiter = cv->first;
798   if (waiter != NULL)
799     {
800       cv->first = waiter->next;
801       if (cv->first == NULL)
802         cv->last_ptr = &cv->first;
803     }
804   LeaveCriticalSection (&g_thread_xp_lock);
805
806   if (waiter != NULL)
807     SetEvent (waiter->event);
808 }
809
810 static void __stdcall
811 g_thread_xp_WakeAllConditionVariable (gpointer cond)
812 {
813   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
814   volatile GThreadXpWaiter *waiter;
815
816   EnterCriticalSection (&g_thread_xp_lock);
817   waiter = cv->first;
818   cv->first = NULL;
819   cv->last_ptr = &cv->first;
820   LeaveCriticalSection (&g_thread_xp_lock);
821
822   while (waiter != NULL)
823     {
824       volatile GThreadXpWaiter *next;
825
826       next = waiter->next;
827       SetEvent (waiter->event);
828       waiter = next;
829     }
830 }
831
832 /* {{{2 XP Setup */
833 static void
834 g_thread_xp_init (void)
835 {
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
851   };
852
853   InitializeCriticalSection (&g_thread_xp_lock);
854   g_thread_xp_waiter_tls = TlsAlloc ();
855
856   g_thread_impl_vtable = g_thread_xp_impl_vtable;
857 }
858
859 /* {{{1 Epilogue */
860
861 void
862 _g_thread_impl_init (void)
863 {
864   static gboolean beenhere = FALSE;
865
866   if (beenhere)
867     return;
868
869   beenhere = TRUE;
870
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 ()));
876 }
877
878 static gboolean
879 g_thread_lookup_native_funcs (void)
880 {
881   GThreadImplVtable native_vtable = { 0, };
882   HMODULE kernel32;
883
884   kernel32 = GetModuleHandle ("KERNEL32.DLL");
885
886   if (kernel32 == NULL)
887     return FALSE;
888
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);
897
898   GET_FUNC(InitializeConditionVariable);
899   GET_FUNC(SleepConditionVariableSRW);
900   GET_FUNC(WakeAllConditionVariable);
901   GET_FUNC(WakeConditionVariable);
902 #undef GET_FUNC
903
904   g_thread_impl_vtable = native_vtable;
905
906   return TRUE;
907 }
908
909 G_GNUC_INTERNAL void
910 g_thread_DllMain (void)
911 {
912   if (g_thread_lookup_native_funcs ())
913     fprintf (stderr, "(debug) GThread using native mode\n");
914   else
915     {
916       fprintf (stderr, "(debug) GThread using Windows XP mode\n");
917       g_thread_xp_init ();
918     }
919 }
920
921 /* vim:set foldmethod=marker: */
922