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