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