1213143a6d86817d6d164ba1e42d833645aa6358
[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 GRWLock */
158
159 void
160 g_rw_lock_init (GRWLock *lock)
161 {
162   g_thread_impl_vtable.InitializeSRWLock (lock);
163 }
164
165 void
166 g_rw_lock_clear (GRWLock *lock)
167 {
168   if (g_thread_impl_vtable.DeleteSRWLock != NULL)
169     g_thread_impl_vtable.DeleteSRWLock (lock);
170 }
171
172 void
173 g_rw_lock_writer_lock (GRWLock *lock)
174 {
175   g_thread_impl_vtable.AcquireSRWLockExclusive (lock);
176 }
177
178 gboolean
179 g_rw_lock_writer_trylock (GRWLock *lock)
180 {
181   return g_thread_impl_vtable.TryAcquireSRWLockExclusive (lock);
182 }
183
184 void
185 g_rw_lock_writer_unlock (GRWLock *lock)
186 {
187   g_thread_impl_vtable.ReleaseSRWLockExclusive (lock);
188 }
189
190 void
191 g_rw_lock_reader_lock (GRWLock *lock)
192 {
193   g_thread_impl_vtable.AcquireSRWLockShared (lock);
194 }
195
196 gboolean
197 g_rw_lock_reader_trylock (GRWLock *lock)
198 {
199   return g_thread_impl_vtable.TryAcquireSRWLockShared (lock);
200 }
201
202 void
203 g_rw_lock_reader_unlock (GRWLock *lock)
204 {
205   g_thread_impl_vtable.ReleaseSRWLockShared (lock);
206 }
207
208 /* {{{1 GCond */
209 void
210 g_cond_init (GCond *cond)
211 {
212   g_thread_impl_vtable.InitializeConditionVariable (cond);
213 }
214
215 void
216 g_cond_clear (GCond *cond)
217 {
218   if (g_thread_impl_vtable.DeleteConditionVariable)
219     g_thread_impl_vtable.DeleteConditionVariable (cond);
220 }
221
222 void
223 g_cond_signal (GCond *cond)
224 {
225   g_thread_impl_vtable.WakeConditionVariable (cond);
226 }
227
228 void
229 g_cond_broadcast (GCond *cond)
230 {
231   g_thread_impl_vtable.WakeAllConditionVariable (cond);
232 }
233
234 void
235 g_cond_wait (GCond  *cond,
236              GMutex *entered_mutex)
237 {
238   g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
239 }
240
241 gboolean
242 g_cond_timedwait (GCond  *cond,
243                   GMutex *entered_mutex,
244                   gint64  abs_time)
245 {
246   gint64 span;
247   FILETIME ft;
248   gint64 now;
249
250   GetSystemTimeAsFileTime (&ft);
251   memmove (&now, &ft, sizeof (FILETIME));
252
253   now -= G_GINT64_CONSTANT (116444736000000000);
254   now /= 10;
255
256   span = abs_time - now;
257
258   if G_UNLIKELY (span < 0)
259     span = 0;
260
261   if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
262     span = INFINITE;
263
264   return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
265 }
266
267 gboolean
268 g_cond_timed_wait (GCond    *cond,
269                    GMutex   *entered_mutex,
270                    GTimeVal *abs_time)
271 {
272   if (abs_time)
273     {
274       gint64 micros;
275
276       micros = abs_time->tv_sec;
277       micros *= 1000000;
278       micros += abs_time->tv_usec;
279
280       return g_cond_timedwait (cond, entered_mutex, micros);
281     }
282   else
283     {
284       g_cond_wait (cond, entered_mutex);
285       return TRUE;
286     }
287 }
288
289 /* {{{1 GPrivate */
290
291 typedef struct _GPrivateDestructor GPrivateDestructor;
292
293 struct _GPrivateDestructor
294 {
295   DWORD               index;
296   GDestroyNotify      notify;
297   GPrivateDestructor *next;
298 };
299
300 static GPrivateDestructor * volatile g_private_destructors;
301
302 void
303 g_private_init (GPrivate       *key,
304                 GDestroyNotify  notify)
305 {
306   GPrivateDestructor *destructor;
307
308   key->index = TlsAlloc ();
309
310   destructor = malloc (sizeof (GPrivateDestructor));
311   if G_UNLIKELY (destructor == NULL)
312     g_thread_abort (errno, "malloc");
313   destructor->index = key->index;
314   destructor->notify = notify;
315
316   do
317     destructor->next = g_private_destructors;
318   while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
319
320   key->ready = TRUE;
321 }
322
323 gpointer
324 g_private_get (GPrivate *key)
325 {
326   if (!key->ready)
327     return key->single_value;
328
329   return TlsGetValue (key->index);
330 }
331
332 void
333 g_private_set (GPrivate *key,
334                gpointer  value)
335 {
336   if (!key->ready)
337     {
338       key->single_value = value;
339       return;
340     }
341
342   TlsSetValue (key->index, value);
343 }
344
345 /* {{{1 GThread */
346
347 #include "glib.h"
348 #include "gthreadprivate.h"
349
350 #define win32_check_for_error(what) G_STMT_START{                       \
351   if (!(what))                                                          \
352     g_error ("file %s: line %d (%s): error %s during %s",               \
353              __FILE__, __LINE__, G_STRFUNC,                             \
354              g_win32_error_message (GetLastError ()), #what);           \
355   }G_STMT_END
356
357 #define G_MUTEX_SIZE (sizeof (gpointer))
358
359 static DWORD g_thread_self_tls;
360 static DWORD g_private_tls;
361
362 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
363
364 typedef struct _GThreadData GThreadData;
365 struct _GThreadData
366 {
367   GThreadFunc func;
368   gpointer data;
369   HANDLE thread;
370   gboolean joinable;
371 };
372
373 void
374 g_system_thread_self (gpointer thread)
375 {
376   GThreadData *self = TlsGetValue (g_thread_self_tls);
377
378   if (!self)
379     {
380       /* This should only happen for the main thread! */
381       HANDLE handle = GetCurrentThread ();
382       HANDLE process = GetCurrentProcess ();
383       self = g_new (GThreadData, 1);
384       win32_check_for_error (DuplicateHandle (process, handle, process,
385                                               &self->thread, 0, FALSE,
386                                               DUPLICATE_SAME_ACCESS));
387       win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
388       self->func = NULL;
389       self->data = NULL;
390       self->joinable = FALSE;
391     }
392
393   *(GThreadData **)thread = self;
394 }
395
396 void
397 g_system_thread_exit (void)
398 {
399   GThreadData *self = TlsGetValue (g_thread_self_tls);
400   gboolean dtors_called;
401
402   do
403     {
404       GPrivateDestructor *dtor;
405
406       /* We go by the POSIX book on this one.
407        *
408        * If we call a destructor then there is a chance that some new
409        * TLS variables got set by code called in that destructor.
410        *
411        * Loop until nothing is left.
412        */
413       dtors_called = FALSE;
414
415       for (dtor = g_private_destructors; dtor; dtor = dtor->next)
416         {
417           gpointer value;
418
419           value = TlsGetValue (dtor->index);
420           if (value != NULL && dtor->notify != NULL)
421             {
422               /* POSIX says to clear this before the call */
423               TlsSetValue (dtor->index, NULL);
424               dtor->notify (value);
425               dtors_called = TRUE;
426             }
427         }
428     }
429   while (dtors_called);
430
431   if (self)
432     {
433       if (!self->joinable)
434         {
435           win32_check_for_error (CloseHandle (self->thread));
436           g_free (self);
437         }
438       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
439     }
440
441   if (g_thread_impl_vtable.CallThisOnThreadExit)
442     g_thread_impl_vtable.CallThisOnThreadExit ();
443
444   _endthreadex (0);
445 }
446
447 static guint __stdcall
448 g_thread_proxy (gpointer data)
449 {
450   GThreadData *self = (GThreadData*) data;
451
452   win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
453
454   self->func (self->data);
455
456   g_system_thread_exit ();
457
458   g_assert_not_reached ();
459
460   return 0;
461 }
462
463 void
464 g_system_thread_create (GThreadFunc       func,
465                         gpointer          data,
466                         gulong            stack_size,
467                         gboolean          joinable,
468                         gpointer          thread,
469                         GError          **error)
470 {
471   guint ignore;
472   GThreadData *retval;
473
474   g_return_if_fail (func);
475
476   retval = g_new(GThreadData, 1);
477   retval->func = func;
478   retval->data = data;
479
480   retval->joinable = joinable;
481
482   retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
483                                             retval, 0, &ignore);
484
485   if (retval->thread == NULL)
486     {
487       gchar *win_error = g_win32_error_message (GetLastError ());
488       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
489                    "Error creating thread: %s", win_error);
490       g_free (retval);
491       g_free (win_error);
492       return;
493     }
494
495   *(GThreadData **)thread = retval;
496 }
497
498 void
499 g_thread_yield (void)
500 {
501   Sleep(0);
502 }
503
504 void
505 g_system_thread_join (gpointer thread)
506 {
507   GThreadData *target = *(GThreadData **)thread;
508
509   g_return_if_fail (target->joinable);
510
511   win32_check_for_error (WAIT_FAILED !=
512                          WaitForSingleObject (target->thread, INFINITE));
513
514   win32_check_for_error (CloseHandle (target->thread));
515   g_free (target);
516 }
517
518 gboolean
519 g_system_thread_equal (gpointer thread1,
520                        gpointer thread2)
521 {
522    return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
523 }
524
525 /* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
526
527 static CRITICAL_SECTION g_thread_xp_lock;
528 static DWORD            g_thread_xp_waiter_tls;
529
530 /* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
531 typedef struct _GThreadXpWaiter GThreadXpWaiter;
532 struct _GThreadXpWaiter
533 {
534   HANDLE                    event;
535   volatile GThreadXpWaiter *next;
536 };
537
538 static GThreadXpWaiter *
539 g_thread_xp_waiter_get (void)
540 {
541   GThreadXpWaiter *waiter;
542
543   waiter = TlsGetValue (g_thread_xp_waiter_tls);
544
545   if G_UNLIKELY (waiter == NULL)
546     {
547       waiter = malloc (sizeof (GThreadXpWaiter));
548       if (waiter == NULL)
549         g_thread_abort (GetLastError (), "malloc");
550       waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
551       if (waiter->event == NULL)
552         g_thread_abort (GetLastError (), "CreateEvent");
553
554       TlsSetValue (g_thread_xp_waiter_tls, waiter);
555     }
556
557   return waiter;
558 }
559
560 static void __stdcall
561 g_thread_xp_CallThisOnThreadExit (void)
562 {
563   GThreadXpWaiter *waiter;
564
565   waiter = TlsGetValue (g_thread_xp_waiter_tls);
566
567   if (waiter != NULL)
568     {
569       TlsSetValue (g_thread_xp_waiter_tls, NULL);
570       CloseHandle (waiter->event);
571       free (waiter);
572     }
573 }
574
575 /* {{{2 SRWLock emulation */
576 typedef struct
577 {
578   CRITICAL_SECTION  writer_lock;
579   gboolean          ever_shared;    /* protected by writer_lock */
580
581   /* below is only ever touched if ever_shared becomes true */
582   CRITICAL_SECTION  atomicity;
583   GThreadXpWaiter  *queued_writer; /* protected by atomicity lock */
584   gint              num_readers;   /* protected by atomicity lock */
585 } GThreadSRWLock;
586
587 static void __stdcall
588 g_thread_xp_InitializeSRWLock (gpointer mutex)
589 {
590   *(GThreadSRWLock * volatile *) mutex = NULL;
591 }
592
593 static void __stdcall
594 g_thread_xp_DeleteSRWLock (gpointer mutex)
595 {
596   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
597
598   if (lock)
599     {
600       if (lock->ever_shared)
601         DeleteCriticalSection (&lock->atomicity);
602
603       DeleteCriticalSection (&lock->writer_lock);
604       free (lock);
605     }
606 }
607
608 static GThreadSRWLock * __stdcall
609 g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
610 {
611   GThreadSRWLock *result;
612
613   /* It looks like we're missing some barriers here, but this code only
614    * ever runs on Windows XP, which in turn only ever runs on hardware
615    * with a relatively rigid memory model.  The 'volatile' will take
616    * care of the compiler.
617    */
618   result = *lock;
619
620   if G_UNLIKELY (result == NULL)
621     {
622       EnterCriticalSection (&g_thread_xp_lock);
623
624       result = malloc (sizeof (GThreadSRWLock));
625
626       if (result == NULL)
627         g_thread_abort (errno, "malloc");
628
629       InitializeCriticalSection (&result->writer_lock);
630       result->ever_shared = FALSE;
631       *lock = result;
632
633       LeaveCriticalSection (&g_thread_xp_lock);
634     }
635
636   return result;
637 }
638
639 static void __stdcall
640 g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
641 {
642   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
643
644   EnterCriticalSection (&lock->writer_lock);
645
646   if (lock->ever_shared)
647     {
648       GThreadXpWaiter *waiter = NULL;
649
650       EnterCriticalSection (&lock->atomicity);
651       if (lock->num_readers > 0)
652         lock->queued_writer = waiter = g_thread_xp_waiter_get ();
653       LeaveCriticalSection (&lock->atomicity);
654
655       if (waiter != NULL)
656         WaitForSingleObject (waiter->event, INFINITE);
657
658       lock->queued_writer = NULL;
659     }
660 }
661
662 static BOOLEAN __stdcall
663 g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
664 {
665   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
666
667   if (!TryEnterCriticalSection (&lock->writer_lock))
668     return FALSE;
669
670   if (lock->ever_shared)
671     {
672       gboolean available;
673
674       EnterCriticalSection (&lock->atomicity);
675       available = lock->num_readers == 0;
676       LeaveCriticalSection (&lock->atomicity);
677
678       if (!available)
679         {
680           LeaveCriticalSection (&lock->writer_lock);
681           return FALSE;
682         }
683     }
684
685   return TRUE;
686 }
687
688 static void __stdcall
689 g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
690 {
691   GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
692
693   /* We need this until we fix some weird parts of GLib that try to
694    * unlock freshly-allocated mutexes.
695    */
696   if (lock != NULL)
697     LeaveCriticalSection (&lock->writer_lock);
698 }
699
700 static void
701 g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
702 {
703   if G_UNLIKELY (!lock->ever_shared)
704     {
705       InitializeCriticalSection (&lock->atomicity);
706       lock->queued_writer = NULL;
707       lock->num_readers = 0;
708
709       lock->ever_shared = TRUE;
710     }
711
712   EnterCriticalSection (&lock->atomicity);
713   lock->num_readers++;
714   LeaveCriticalSection (&lock->atomicity);
715 }
716
717 static void __stdcall
718 g_thread_xp_AcquireSRWLockShared (gpointer mutex)
719 {
720   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
721
722   EnterCriticalSection (&lock->writer_lock);
723
724   g_thread_xp_srwlock_become_reader (lock);
725
726   LeaveCriticalSection (&lock->writer_lock);
727 }
728
729 static BOOLEAN __stdcall
730 g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
731 {
732   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
733
734   if (!TryEnterCriticalSection (&lock->writer_lock))
735     return FALSE;
736
737   g_thread_xp_srwlock_become_reader (lock);
738
739   LeaveCriticalSection (&lock->writer_lock);
740
741   return TRUE;
742 }
743
744 static void __stdcall
745 g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
746 {
747   GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
748
749   EnterCriticalSection (&lock->atomicity);
750
751   lock->num_readers--;
752
753   if (lock->num_readers == 0 && lock->queued_writer)
754     SetEvent (lock->queued_writer->event);
755
756   LeaveCriticalSection (&lock->atomicity);
757 }
758
759 /* {{{2 CONDITION_VARIABLE emulation */
760 typedef struct
761 {
762   volatile GThreadXpWaiter  *first;
763   volatile GThreadXpWaiter **last_ptr;
764 } GThreadXpCONDITION_VARIABLE;
765
766 static void __stdcall
767 g_thread_xp_InitializeConditionVariable (gpointer cond)
768 {
769   *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
770 }
771
772 static void __stdcall
773 g_thread_xp_DeleteConditionVariable (gpointer cond)
774 {
775   GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
776
777   if (cv)
778     free (cv);
779 }
780
781 static GThreadXpCONDITION_VARIABLE * __stdcall
782 g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
783 {
784   GThreadXpCONDITION_VARIABLE *result;
785
786   /* It looks like we're missing some barriers here, but this code only
787    * ever runs on Windows XP, which in turn only ever runs on hardware
788    * with a relatively rigid memory model.  The 'volatile' will take
789    * care of the compiler.
790    */
791   result = *cond;
792
793   if G_UNLIKELY (result == NULL)
794     {
795       result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
796
797       if (result == NULL)
798         g_thread_abort (errno, "malloc");
799
800       result->first = NULL;
801       result->last_ptr = &result->first;
802
803       if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
804         {
805           free (result);
806           result = *cond;
807         }
808     }
809
810   return result;
811 }
812
813 static BOOL __stdcall
814 g_thread_xp_SleepConditionVariableSRW (gpointer cond,
815                                        gpointer mutex,
816                                        DWORD    timeout,
817                                        ULONG    flags)
818 {
819   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
820   GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
821   DWORD status;
822
823   waiter->next = NULL;
824
825   EnterCriticalSection (&g_thread_xp_lock);
826   *cv->last_ptr = waiter;
827   cv->last_ptr = &waiter->next;
828   LeaveCriticalSection (&g_thread_xp_lock);
829
830   g_mutex_unlock (mutex);
831   status = WaitForSingleObject (waiter->event, timeout);
832
833   if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
834     g_thread_abort (GetLastError (), "WaitForSingleObject");
835
836   g_mutex_lock (mutex);
837
838   return status == WAIT_OBJECT_0;
839 }
840
841 static void __stdcall
842 g_thread_xp_WakeConditionVariable (gpointer cond)
843 {
844   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
845   volatile GThreadXpWaiter *waiter;
846
847   EnterCriticalSection (&g_thread_xp_lock);
848   waiter = cv->first;
849   if (waiter != NULL)
850     {
851       cv->first = waiter->next;
852       if (cv->first == NULL)
853         cv->last_ptr = &cv->first;
854     }
855   LeaveCriticalSection (&g_thread_xp_lock);
856
857   if (waiter != NULL)
858     SetEvent (waiter->event);
859 }
860
861 static void __stdcall
862 g_thread_xp_WakeAllConditionVariable (gpointer cond)
863 {
864   GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
865   volatile GThreadXpWaiter *waiter;
866
867   EnterCriticalSection (&g_thread_xp_lock);
868   waiter = cv->first;
869   cv->first = NULL;
870   cv->last_ptr = &cv->first;
871   LeaveCriticalSection (&g_thread_xp_lock);
872
873   while (waiter != NULL)
874     {
875       volatile GThreadXpWaiter *next;
876
877       next = waiter->next;
878       SetEvent (waiter->event);
879       waiter = next;
880     }
881 }
882
883 /* {{{2 XP Setup */
884 static void
885 g_thread_xp_init (void)
886 {
887   static const GThreadImplVtable g_thread_xp_impl_vtable = {
888     g_thread_xp_CallThisOnThreadExit,
889     g_thread_xp_InitializeSRWLock,
890     g_thread_xp_DeleteSRWLock,
891     g_thread_xp_AcquireSRWLockExclusive,
892     g_thread_xp_TryAcquireSRWLockExclusive,
893     g_thread_xp_ReleaseSRWLockExclusive,
894     g_thread_xp_AcquireSRWLockShared,
895     g_thread_xp_TryAcquireSRWLockShared,
896     g_thread_xp_ReleaseSRWLockShared,
897     g_thread_xp_InitializeConditionVariable,
898     g_thread_xp_DeleteConditionVariable,
899     g_thread_xp_SleepConditionVariableSRW,
900     g_thread_xp_WakeAllConditionVariable,
901     g_thread_xp_WakeConditionVariable
902   };
903
904   InitializeCriticalSection (&g_thread_xp_lock);
905   g_thread_xp_waiter_tls = TlsAlloc ();
906
907   g_thread_impl_vtable = g_thread_xp_impl_vtable;
908 }
909
910 /* {{{1 Epilogue */
911
912 static gboolean
913 g_thread_lookup_native_funcs (void)
914 {
915   GThreadImplVtable native_vtable = { 0, };
916   HMODULE kernel32;
917
918   kernel32 = GetModuleHandle ("KERNEL32.DLL");
919
920   if (kernel32 == NULL)
921     return FALSE;
922
923 #define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
924   GET_FUNC(InitializeSRWLock);
925   GET_FUNC(AcquireSRWLockExclusive);
926   GET_FUNC(TryAcquireSRWLockExclusive);
927   GET_FUNC(ReleaseSRWLockExclusive);
928   GET_FUNC(AcquireSRWLockShared);
929   GET_FUNC(TryAcquireSRWLockShared);
930   GET_FUNC(ReleaseSRWLockShared);
931
932   GET_FUNC(InitializeConditionVariable);
933   GET_FUNC(SleepConditionVariableSRW);
934   GET_FUNC(WakeAllConditionVariable);
935   GET_FUNC(WakeConditionVariable);
936 #undef GET_FUNC
937
938   g_thread_impl_vtable = native_vtable;
939
940   return TRUE;
941 }
942
943 G_GNUC_INTERNAL void
944 g_thread_DllMain (void)
945 {
946   if (g_thread_lookup_native_funcs ())
947     fprintf (stderr, "(debug) GThread using native mode\n");
948   else
949     {
950       fprintf (stderr, "(debug) GThread using Windows XP mode\n");
951       g_thread_xp_init ();
952     }
953
954   win32_check_for_error (TLS_OUT_OF_INDEXES != (g_thread_self_tls = TlsAlloc ()));
955   win32_check_for_error (TLS_OUT_OF_INDEXES != (g_private_tls = TlsAlloc ()));
956 }
957
958 /* vim:set foldmethod=marker: */
959