Port g_cond_new to use GSlice
[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
47 #define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
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     (* CallThisOnThreadExit)        (void);              /* fake */
103
104   void     (* InitializeSRWLock)           (gpointer lock);
105   void     (* DeleteSRWLock)               (gpointer lock);     /* fake */
106   void     (* AcquireSRWLockExclusive)     (gpointer lock);
107   BOOLEAN  (* TryAcquireSRWLockExclusive)  (gpointer lock);
108   void     (* ReleaseSRWLockExclusive)     (gpointer lock);
109
110   void     (* InitializeConditionVariable) (gpointer cond);
111   void     (* DeleteConditionVariable)     (gpointer cond);     /* fake */
112   BOOL     (* SleepConditionVariableSRW)   (gpointer cond,
113                                             gpointer lock,
114                                             DWORD    timeout,
115                                             ULONG    flags);
116   void     (* WakeAllConditionVariable)    (gpointer cond);
117   void     (* WakeConditionVariable)       (gpointer cond);
118 } GThreadImplVtable;
119
120 static GThreadImplVtable g_thread_impl_vtable;
121
122 /* {{{1 GMutex */
123 void
124 g_mutex_init (GMutex *mutex)
125 {
126   g_thread_impl_vtable.InitializeSRWLock (mutex);
127 }
128
129 void
130 g_mutex_clear (GMutex *mutex)
131 {
132   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
133     g_thread_impl_vtable.DeleteSRWLock (mutex);
134 }
135
136 void
137 g_mutex_lock (GMutex *mutex)
138 {
139   /* temporary until we fix libglib */
140   if (mutex == NULL)
141     return;
142
143   g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
144 }
145
146 gboolean
147 g_mutex_trylock (GMutex *mutex)
148 {
149   /* temporary until we fix libglib */
150   if (mutex == NULL)
151     return TRUE;
152
153   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
154 }
155
156 void
157 g_mutex_unlock (GMutex *mutex)
158 {
159   /* temporary until we fix libglib */
160   if (mutex == NULL)
161     return;
162
163   g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
164 }
165
166 /* {{{1 GCond */
167 void
168 g_cond_init (GCond *cond)
169 {
170   g_thread_impl_vtable.InitializeConditionVariable (cond);
171 }
172
173 void
174 g_cond_clear (GCond *cond)
175 {
176   if (g_thread_impl_vtable.DeleteConditionVariable)
177     g_thread_impl_vtable.DeleteConditionVariable (cond);
178 }
179
180 void
181 g_cond_signal (GCond *cond)
182 {
183   /* temporary until we fix libglib */
184   if (cond == NULL)
185     return;
186
187   g_thread_impl_vtable.WakeConditionVariable (cond);
188 }
189
190 void
191 g_cond_broadcast (GCond *cond)
192 {
193   /* temporary until we fix libglib */
194   if (cond == NULL)
195     return;
196
197   g_thread_impl_vtable.WakeAllConditionVariable (cond);
198 }
199
200 void
201 g_cond_wait (GCond  *cond,
202              GMutex *entered_mutex)
203 {
204   g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
205 }
206
207 gboolean
208 g_cond_timedwait (GCond  *cond,
209                   GMutex *entered_mutex,
210                   gint64  abs_time)
211 {
212   gint64 span;
213   FILETIME ft;
214   gint64 now;
215
216   GetSystemTimeAsFileTime (&ft);
217   memmove (&now, &ft, sizeof (FILETIME));
218
219   now -= G_GINT64_CONSTANT (116444736000000000);
220   now /= 10;
221
222   span = abs_time - now;
223
224   if G_UNLIKELY (span < 0)
225     span = 0;
226
227   if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
228     span = INFINITE;
229
230   return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
231 }
232
233 gboolean
234 g_cond_timed_wait (GCond    *cond,
235                    GMutex   *entered_mutex,
236                    GTimeVal *abs_time)
237 {
238   if (abs_time)
239     {
240       gint64 micros;
241
242       micros = abs_time->tv_sec;
243       micros *= 1000000;
244       micros += abs_time->tv_usec;
245
246       return g_cond_timedwait (cond, entered_mutex, micros);
247     }
248   else
249     {
250       g_cond_wait (cond, entered_mutex);
251       return TRUE;
252     }
253 }
254
255 /* {{{1 GPrivate */
256
257 #include "glib.h"
258 #include "gthreadprivate.h"
259
260 #define win32_check_for_error(what) G_STMT_START{                       \
261   if (!(what))                                                          \
262     g_error ("file %s: line %d (%s): error %s during %s",               \
263              __FILE__, __LINE__, G_STRFUNC,                             \
264              g_win32_error_message (GetLastError ()), #what);           \
265   }G_STMT_END
266
267 #define G_MUTEX_SIZE (sizeof (gpointer))
268
269 static DWORD g_thread_self_tls;
270 static DWORD g_private_tls;
271 static CRITICAL_SECTION g_thread_global_spinlock;
272
273 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
274
275 /* As noted in the docs, GPrivate is a limited resource, here we take
276  * a rather low maximum to save memory, use GStaticPrivate instead. */
277 #define G_PRIVATE_MAX 100
278
279 static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
280
281 static guint g_private_next = 0;
282
283 typedef struct _GThreadData GThreadData;
284 struct _GThreadData
285 {
286   GThreadFunc func;
287   gpointer data;
288   HANDLE thread;
289   gboolean joinable;
290 };
291
292 static GPrivate *
293 g_private_new_win32_impl (GDestroyNotify destructor)
294 {
295   GPrivate *result;
296   EnterCriticalSection (&g_thread_global_spinlock);
297   if (g_private_next >= G_PRIVATE_MAX)
298     {
299       char buf[100];
300       sprintf (buf,
301                "Too many GPrivate allocated. Their number is limited to %d.",
302                G_PRIVATE_MAX);
303       MessageBox (NULL, buf, NULL, MB_ICONERROR|MB_SETFOREGROUND);
304       if (IsDebuggerPresent ())
305         G_BREAKPOINT ();
306       abort ();
307     }
308   g_private_destructors[g_private_next] = destructor;
309   result = GUINT_TO_POINTER (g_private_next);
310   g_private_next++;
311   LeaveCriticalSection (&g_thread_global_spinlock);
312
313   return result;
314 }
315
316 /* NOTE: the functions g_private_get and g_private_set may not use
317    functions from gmem.c and gmessages.c */
318
319 static void
320 g_private_set_win32_impl (GPrivate * private_key, gpointer value)
321 {
322   gpointer* array = TlsGetValue (g_private_tls);
323   guint index = GPOINTER_TO_UINT (private_key);
324
325   if (index >= G_PRIVATE_MAX)
326       return;
327
328   if (!array)
329     {
330       array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
331       TlsSetValue (g_private_tls, array);
332     }
333
334   array[index] = value;
335 }
336
337 static gpointer
338 g_private_get_win32_impl (GPrivate * private_key)
339 {
340   gpointer* array = TlsGetValue (g_private_tls);
341   guint index = GPOINTER_TO_UINT (private_key);
342
343   if (index >= G_PRIVATE_MAX || !array)
344     return NULL;
345
346   return array[index];
347 }
348
349 /* {{{1 GThread */
350
351 static void
352 g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
353 {
354   GThreadData *target = *(GThreadData **)thread;
355   gint native_prio;
356
357   switch (priority)
358     {
359     case G_THREAD_PRIORITY_LOW:
360       native_prio = THREAD_PRIORITY_BELOW_NORMAL;
361       break;
362
363     case G_THREAD_PRIORITY_NORMAL:
364       native_prio = THREAD_PRIORITY_NORMAL;
365       break;
366
367     case G_THREAD_PRIORITY_HIGH:
368       native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
369       break;
370
371     case G_THREAD_PRIORITY_URGENT:
372       native_prio = THREAD_PRIORITY_HIGHEST;
373       break;
374
375     default:
376       g_return_if_reached ();
377     }
378
379   win32_check_for_error (SetThreadPriority (target->thread, native_prio));
380 }
381
382 static void
383 g_thread_self_win32_impl (gpointer thread)
384 {
385   GThreadData *self = TlsGetValue (g_thread_self_tls);
386
387   if (!self)
388     {
389       /* This should only happen for the main thread! */
390       HANDLE handle = GetCurrentThread ();
391       HANDLE process = GetCurrentProcess ();
392       self = g_new (GThreadData, 1);
393       win32_check_for_error (DuplicateHandle (process, handle, process,
394                                               &self->thread, 0, FALSE,
395                                               DUPLICATE_SAME_ACCESS));
396       win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
397       self->func = NULL;
398       self->data = NULL;
399       self->joinable = FALSE;
400     }
401
402   *(GThreadData **)thread = self;
403 }
404
405 static void
406 g_thread_exit_win32_impl (void)
407 {
408   GThreadData *self = TlsGetValue (g_thread_self_tls);
409   guint i, private_max;
410   gpointer *array = TlsGetValue (g_private_tls);
411
412   EnterCriticalSection (&g_thread_global_spinlock);
413   private_max = g_private_next;
414   LeaveCriticalSection (&g_thread_global_spinlock);
415
416   if (array)
417     {
418       gboolean some_data_non_null;
419
420       do {
421         some_data_non_null = FALSE;
422         for (i = 0; i < private_max; i++)
423           {
424             GDestroyNotify destructor = g_private_destructors[i];
425             GDestroyNotify data = array[i];
426
427             if (data)
428               some_data_non_null = TRUE;
429
430             array[i] = NULL;
431
432             if (destructor && data)
433               destructor (data);
434           }
435       } while (some_data_non_null);
436
437       free (array);
438
439       win32_check_for_error (TlsSetValue (g_private_tls, NULL));
440     }
441
442   if (self)
443     {
444       if (!self->joinable)
445         {
446           win32_check_for_error (CloseHandle (self->thread));
447           g_free (self);
448         }
449       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
450     }
451
452   if (g_thread_impl_vtable.CallThisOnThreadExit)
453     g_thread_impl_vtable.CallThisOnThreadExit ();
454
455   _endthreadex (0);
456 }
457
458 static guint __stdcall
459 g_thread_proxy (gpointer data)
460 {
461   GThreadData *self = (GThreadData*) data;
462
463   win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
464
465   self->func (self->data);
466
467   g_thread_exit_win32_impl ();
468
469   g_assert_not_reached ();
470
471   return 0;
472 }
473
474 static void
475 g_thread_create_win32_impl (GThreadFunc func,
476                             gpointer data,
477                             gulong stack_size,
478                             gboolean joinable,
479                             gboolean bound,
480                             GThreadPriority priority,
481                             gpointer thread,
482                             GError **error)
483 {
484   guint ignore;
485   GThreadData *retval;
486
487   g_return_if_fail (func);
488   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
489   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
490
491   retval = g_new(GThreadData, 1);
492   retval->func = func;
493   retval->data = data;
494
495   retval->joinable = joinable;
496
497   retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
498                                             retval, 0, &ignore);
499
500   if (retval->thread == NULL)
501     {
502       gchar *win_error = g_win32_error_message (GetLastError ());
503       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
504                    "Error creating thread: %s", win_error);
505       g_free (retval);
506       g_free (win_error);
507       return;
508     }
509
510   *(GThreadData **)thread = retval;
511
512   g_thread_set_priority_win32_impl (thread, priority);
513 }
514
515 static void
516 g_thread_yield_win32_impl (void)
517 {
518   Sleep(0);
519 }
520
521 static void
522 g_thread_join_win32_impl (gpointer thread)
523 {
524   GThreadData *target = *(GThreadData **)thread;
525
526   g_return_if_fail (target->joinable);
527
528   win32_check_for_error (WAIT_FAILED !=
529                          WaitForSingleObject (target->thread, INFINITE));
530
531   win32_check_for_error (CloseHandle (target->thread));
532   g_free (target);
533 }
534
535 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
536
537 static DWORD            g_thread_xp_waiter_tls;
538 static CRITICAL_SECTION g_thread_xp_lock;
539
540 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
541 typedef struct _GThreadXpWaiter GThreadXpWaiter;
542 struct _GThreadXpWaiter
543 {
544   HANDLE                    event;
545   volatile GThreadXpWaiter *next;
546 };
547
548 static GThreadXpWaiter *
549 g_thread_xp_waiter_get (void)
550 {
551   GThreadXpWaiter *waiter;
552
553   waiter = TlsGetValue (g_thread_xp_waiter_tls);
554
555   if G_UNLIKELY (waiter == NULL)
556     {
557       waiter = malloc (sizeof (GThreadXpWaiter));
558       if (waiter == NULL)
559         g_thread_abort (GetLastError (), "malloc");
560       waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
561       if (waiter->event == NULL)
562         g_thread_abort (GetLastError (), "CreateEvent");
563
564       TlsSetValue (g_thread_xp_waiter_tls, waiter);
565     }
566
567   return waiter;
568 }
569
570 static void
571 g_thread_xp_CallThisOnThreadExit (void)
572 {
573   GThreadXpWaiter *waiter;
574
575   waiter = TlsGetValue (g_thread_xp_waiter_tls);
576
577   if (waiter != NULL)
578     {
579       TlsSetValue (g_thread_xp_waiter_tls, NULL);
580       CloseHandle (waiter->event);
581       free (waiter);
582     }
583 }
584
585 /* {{{2 SRWLock emulation */
586 typedef struct
587 {
588   CRITICAL_SECTION critical_section;
589 } GThreadSRWLock;
590
591 static void
592 g_thread_xp_InitializeSRWLock (gpointer mutex)
593 {
594   *(GThreadSRWLock * volatile *) mutex = NULL;
595 }
596
597 static void
598 g_thread_xp_DeleteSRWLock (gpointer mutex)
599 {
600   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
601
602   if (lock)
603     {
604       DeleteCriticalSection (&lock->critical_section);
605       free (lock);
606     }
607 }
608
609 static GThreadSRWLock *
610 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
611 {
612   GThreadSRWLock *result;
613
614   /* It looks like we're missing some barriers here, but this code only
615    * ever runs on Windows XP, which in turn only ever runs on hardware
616    * with a relatively rigid memory model.  The 'volatile' will take
617    * care of the compiler.
618    */
619   result = *lock;
620
621   if G_UNLIKELY (result == NULL)
622     {
623       EnterCriticalSection (&g_thread_xp_lock);
624
625       result = malloc (sizeof (GThreadSRWLock));
626
627       if (result == NULL)
628         g_thread_abort (errno, "malloc");
629
630       InitializeCriticalSection (&result->critical_section);
631       *lock = result;
632
633       LeaveCriticalSection (&g_thread_xp_lock);
634     }
635
636   return result;
637 }
638
639 static void
640 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
641 {
642   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
643
644   EnterCriticalSection (&lock->critical_section);
645 }
646
647 static BOOLEAN
648 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
649 {
650   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
651
652   return TryEnterCriticalSection (&lock->critical_section);
653 }
654
655 static void
656 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
657 {
658   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
659
660   /* We need this until we fix some weird parts of GLib that try to
661    * unlock freshly-allocated mutexes.
662    */
663   if (lock != NULL)
664     LeaveCriticalSection (&lock->critical_section);
665 }
666
667 /* {{{2 CONDITION_VARIABLE emulation */
668 typedef struct
669 {
670   volatile GThreadXpWaiter  *first;
671   volatile GThreadXpWaiter **last_ptr;
672 } GThreadXpCONDITION_VARIABLE;
673
674 static void
675 g_thread_xp_InitializeConditionVariable (gpointer cond)
676 {
677   *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
678 }
679
680 static void
681 g_thread_xp_DeleteConditionVariable (gpointer cond)
682 {
683   GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
684
685   if (cv)
686     free (cv);
687 }
688
689 static GThreadXpCONDITION_VARIABLE *
690 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
691 {
692   GThreadXpCONDITION_VARIABLE *result;
693
694   /* It looks like we're missing some barriers here, but this code only
695    * ever runs on Windows XP, which in turn only ever runs on hardware
696    * with a relatively rigid memory model.  The 'volatile' will take
697    * care of the compiler.
698    */
699   result = *cond;
700
701   if G_UNLIKELY (result == NULL)
702     {
703       result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
704
705       if (result == NULL)
706         g_thread_abort (errno, "malloc");
707
708       result->first = NULL;
709       result->last_ptr = &result->first;
710
711       if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
712         {
713           free (result);
714           result = *cond;
715         }
716     }
717
718   return result;
719 }
720
721 static BOOL
722 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
723                                        gpointer mutex,
724                                        DWORD    timeout,
725                                        ULONG    flags)
726 {
727   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
728   GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
729   DWORD status;
730
731   waiter->next = NULL;
732
733   EnterCriticalSection (&g_thread_xp_lock);
734   *cv->last_ptr = waiter;
735   cv->last_ptr = &waiter->next;
736   LeaveCriticalSection (&g_thread_xp_lock);
737
738   g_mutex_unlock (mutex);
739   status = WaitForSingleObject (waiter->event, timeout);
740
741   if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
742     g_thread_abort (GetLastError (), "WaitForSingleObject");
743
744   g_mutex_lock (mutex);
745
746   return status == WAIT_OBJECT_0;
747 }
748
749 static void
750 g_thread_xp_WakeConditionVariable (gpointer cond)
751 {
752   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
753   volatile GThreadXpWaiter *waiter;
754
755   EnterCriticalSection (&g_thread_xp_lock);
756   waiter = cv->first;
757   if (waiter != NULL)
758     {
759       cv->first = waiter->next;
760       if (cv->first == NULL)
761         cv->last_ptr = &cv->first;
762     }
763   LeaveCriticalSection (&g_thread_xp_lock);
764
765   if (waiter != NULL)
766     SetEvent (waiter->event);
767 }
768
769 static void
770 g_thread_xp_WakeAllConditionVariable (gpointer cond)
771 {
772   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
773   volatile GThreadXpWaiter *waiter;
774
775   EnterCriticalSection (&g_thread_xp_lock);
776   waiter = cv->first;
777   cv->first = NULL;
778   cv->last_ptr = &cv->first;
779   LeaveCriticalSection (&g_thread_xp_lock);
780
781   while (waiter != NULL)
782     {
783       volatile GThreadXpWaiter *next;
784
785       next = waiter->next;
786       SetEvent (waiter->event);
787       waiter = next;
788     }
789 }
790
791 /* {{{2 XP Setup */
792 static void
793 g_thread_xp_init (void)
794 {
795   static const GThreadImplVtable g_thread_xp_impl_vtable = {
796     g_thread_xp_CallThisOnThreadExit,
797     g_thread_xp_InitializeSRWLock,
798     g_thread_xp_DeleteSRWLock,
799     g_thread_xp_AcquireSRWLockExclusive,
800     g_thread_xp_TryAcquireSRWLockExclusive,
801     g_thread_xp_ReleaseSRWLockExclusive,
802     g_thread_xp_InitializeConditionVariable,
803     g_thread_xp_DeleteConditionVariable,
804     g_thread_xp_SleepConditionVariableSRW,
805     g_thread_xp_WakeAllConditionVariable,
806     g_thread_xp_WakeConditionVariable
807   };
808
809   InitializeCriticalSection (&g_thread_xp_lock);
810   g_thread_xp_waiter_tls = TlsAlloc ();
811
812   g_thread_impl_vtable = g_thread_xp_impl_vtable;
813 }
814
815 /* {{{1 Epilogue */
816
817 GThreadFunctions g_thread_functions_for_glib_use =
818 {
819   g_mutex_new,           /* mutex */
820   g_mutex_lock,
821   g_mutex_trylock,
822   g_mutex_unlock,
823   g_mutex_free,
824   g_cond_new,            /* condition */
825   g_cond_signal,
826   g_cond_broadcast,
827   g_cond_wait,
828   g_cond_timed_wait,
829   g_cond_free,
830   g_private_new_win32_impl,         /* private thread data */
831   g_private_get_win32_impl,
832   g_private_set_win32_impl,
833   g_thread_create_win32_impl,       /* thread */
834   g_thread_yield_win32_impl,
835   g_thread_join_win32_impl,
836   g_thread_exit_win32_impl,
837   g_thread_set_priority_win32_impl,
838   g_thread_self_win32_impl,
839   NULL                             /* no equal function necessary */
840 };
841
842 void
843 _g_thread_impl_init (void)
844 {
845   static gboolean beenhere = FALSE;
846
847   if (beenhere)
848     return;
849
850   beenhere = TRUE;
851
852   printf ("thread init\n");
853   win32_check_for_error (TLS_OUT_OF_INDEXES !=
854                          (g_thread_self_tls = TlsAlloc ()));
855   win32_check_for_error (TLS_OUT_OF_INDEXES !=
856                          (g_private_tls = TlsAlloc ()));
857   InitializeCriticalSection (&g_thread_global_spinlock);
858 }
859
860 static gboolean
861 g_thread_lookup_native_funcs (void)
862 {
863   GThreadImplVtable native_vtable = { 0, };
864   HMODULE kernel32;
865
866   kernel32 = GetModuleHandle ("KERNEL32.DLL");
867
868   if (kernel32 == NULL)
869     return FALSE;
870
871 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
872   GET_FUNC(InitializeSRWLock);
873   GET_FUNC(AcquireSRWLockExclusive);
874   GET_FUNC(TryAcquireSRWLockExclusive);
875   GET_FUNC(ReleaseSRWLockExclusive);
876
877   GET_FUNC(InitializeConditionVariable);
878   GET_FUNC(SleepConditionVariableSRW);
879   GET_FUNC(WakeAllConditionVariable);
880   GET_FUNC(WakeConditionVariable);
881 #undef GET_FUNC
882
883   g_thread_impl_vtable = native_vtable;
884
885   return TRUE;
886 }
887
888 G_GNUC_INTERNAL void
889 g_thread_DllMain (void)
890 {
891   /* XXX This is broken right now for some unknown reason...
892
893   if (g_thread_lookup_native_funcs ())
894     fprintf (stderr, "(debug) GThread using native mode\n");
895   else
896 */
897     {
898       fprintf (stderr, "(debug) GThread using Windows XP mode\n");
899       g_thread_xp_init ();
900     }
901 }
902
903 /* vim:set foldmethod=marker: */
904