Add a new recursive mutex type, GRecMutex
[platform/upstream/glib.git] / glib / gthread-win32.c
index d50aee1..f1533c7 100644 (file)
  * GLib at ftp://ftp.gtk.org/pub/gtk/.
  */
 
-/*
- * MT safe
+/* The GMutex and GCond implementations in this file are some of the
+ * lowest-level code in GLib.  All other parts of GLib (messages,
+ * memory, slices, etc) assume that they can freely use these facilities
+ * without risking recursion.
+ *
+ * As such, these functions are NOT permitted to call any other part of
+ * GLib.
+ *
+ * The thread manipulation functions (create, exit, join, etc.) have
+ * more freedom -- they can do as they please.
  */
 
 #include "config.h"
 
-#include "glib.h"
+#include "gthread.h"
 #include "gthreadprivate.h"
+#include "gslice.h"
 
-#define STRICT
-#define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
 #include <windows.h>
-#undef STRICT
 
 #include <process.h>
 #include <stdlib.h>
 #include <stdio.h>
 
-#define win32_check_for_error(what) G_STMT_START{                      \
-  if (!(what))                                                         \
-    g_error ("file %s: line %d (%s): error %s during %s",              \
-            __FILE__, __LINE__, G_STRFUNC,                             \
-            g_win32_error_message (GetLastError ()), #what);           \
-  }G_STMT_END
-
-#define G_MUTEX_SIZE (sizeof (gpointer))
-
-static DWORD g_thread_self_tls;
-static DWORD g_private_tls;
-static DWORD g_cond_event_tls;
-static CRITICAL_SECTION g_thread_global_spinlock;
-
-typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
+static void
+g_thread_abort (gint         status,
+                const gchar *function)
+{
+  fprintf (stderr, "GLib (gthread-win32.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
+           strerror (status), function);
+  abort ();
+}
 
-/* As noted in the docs, GPrivate is a limited resource, here we take
- * a rather low maximum to save memory, use GStaticPrivate instead. */
-#define G_PRIVATE_MAX 100
+/* Starting with Vista and Windows 2008, we have access to the
+ * CONDITION_VARIABLE and SRWLock primatives on Windows, which are
+ * pretty reasonable approximations of the primatives specified in
+ * POSIX 2001 (pthread_cond_t and pthread_mutex_t respectively).
+ *
+ * Both of these types are structs containing a single pointer.  That
+ * pointer is used as an atomic bitfield to support user-space mutexes
+ * that only get the kernel involved in cases of contention (similar
+ * to how futex()-based mutexes work on Linux).  The biggest advantage
+ * of these new types is that they can be statically initialised to
+ * zero.  This allows us to use them directly and still support:
+ *
+ *   GMutex mutex = G_MUTEX_INIT;
+ *
+ * and
+ *
+ *   GCond cond = G_COND_INIT;
+ *
+ * Unfortunately, Windows XP lacks these facilities and GLib still
+ * needs to support Windows XP.  Our approach here is as follows:
+ *
+ *   - avoid depending on structure declarations at compile-time by
+ *     declaring our own GMutex and GCond strutures to be
+ *     ABI-compatible with SRWLock and CONDITION_VARIABLE and using
+ *     those instead
+ *
+ *   - avoid a hard dependency on the symbols used to manipulate these
+ *     structures by doing a dynamic lookup of those symbols at
+ *     runtime
+ *
+ *   - if the symbols are not available, emulate them using other
+ *     primatives
+ *
+ * Using this approach also allows us to easily build a GLib that lacks
+ * support for Windows XP or to remove this code entirely when XP is no
+ * longer supported (end of line is currently April 8, 2014).
+ */
+typedef struct
+{
+  void     (__stdcall * CallThisOnThreadExit)        (void);              /* fake */
+
+  void     (__stdcall * InitializeSRWLock)           (gpointer lock);
+  void     (__stdcall * DeleteSRWLock)               (gpointer lock);     /* fake */
+  void     (__stdcall * AcquireSRWLockExclusive)     (gpointer lock);
+  BOOLEAN  (__stdcall * TryAcquireSRWLockExclusive)  (gpointer lock);
+  void     (__stdcall * ReleaseSRWLockExclusive)     (gpointer lock);
+  void     (__stdcall * AcquireSRWLockShared)        (gpointer lock);
+  BOOLEAN  (__stdcall * TryAcquireSRWLockShared)     (gpointer lock);
+  void     (__stdcall * ReleaseSRWLockShared)        (gpointer lock);
+
+  void     (__stdcall * InitializeConditionVariable) (gpointer cond);
+  void     (__stdcall * DeleteConditionVariable)     (gpointer cond);     /* fake */
+  BOOL     (__stdcall * SleepConditionVariableSRW)   (gpointer cond,
+                                                      gpointer lock,
+                                                      DWORD    timeout,
+                                                      ULONG    flags);
+  void     (__stdcall * WakeAllConditionVariable)    (gpointer cond);
+  void     (__stdcall * WakeConditionVariable)       (gpointer cond);
+} GThreadImplVtable;
+
+static GThreadImplVtable g_thread_impl_vtable;
+
+/* {{{1 GMutex */
+void
+g_mutex_init (GMutex *mutex)
+{
+  g_thread_impl_vtable.InitializeSRWLock (mutex);
+}
 
-static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
+void
+g_mutex_clear (GMutex *mutex)
+{
+  if (g_thread_impl_vtable.DeleteSRWLock != NULL)
+    g_thread_impl_vtable.DeleteSRWLock (mutex);
+}
 
-static guint g_private_next = 0;
+void
+g_mutex_lock (GMutex *mutex)
+{
+  g_thread_impl_vtable.AcquireSRWLockExclusive (mutex);
+}
 
-typedef struct _GThreadData GThreadData;
-struct _GThreadData
+gboolean
+g_mutex_trylock (GMutex *mutex)
 {
-  GThreadFunc func;
-  gpointer data;
-  HANDLE thread;
-  gboolean joinable;
-};
+  return g_thread_impl_vtable.TryAcquireSRWLockExclusive (mutex);
+}
 
-struct _GCond
+void
+g_mutex_unlock (GMutex *mutex)
 {
-  GPtrArray *array;
-  CRITICAL_SECTION lock;
-};
+  g_thread_impl_vtable.ReleaseSRWLockExclusive (mutex);
+}
 
-static GMutex *
-g_mutex_new_win32_impl (void)
+/* {{{1 GRecMutex */
+
+static CRITICAL_SECTION *
+g_rec_mutex_impl_new (void)
 {
-  CRITICAL_SECTION *cs = g_new (CRITICAL_SECTION, 1);
-  gpointer *retval = g_new (gpointer, 1);
+  CRITICAL_SECTION *cs;
 
+  cs = g_slice_new (CRITICAL_SECTION);
   InitializeCriticalSection (cs);
-  *retval = cs;
-  return (GMutex *) retval;
+
+  return cs;
 }
 
 static void
-g_mutex_free_win32_impl (GMutex *mutex)
+g_rec_mutex_impl_free (CRITICAL_SECTION *cs)
 {
-  gpointer *ptr = (gpointer *) mutex;
-  CRITICAL_SECTION *cs = (CRITICAL_SECTION *) *ptr;
-
   DeleteCriticalSection (cs);
-  g_free (cs);
-  g_free (mutex);
+  g_slice_free (CRITICAL_SECTION, cs);
 }
 
-/* NOTE: the functions g_mutex_lock and g_mutex_unlock may not use
-   functions from gmem.c and gmessages.c; */
-
-static void
-g_mutex_lock_win32_impl (GMutex *mutex)
+static CRITICAL_SECTION *
+g_rec_mutex_get_impl (GRecMutex *mutex)
 {
-  EnterCriticalSection (*(CRITICAL_SECTION **)mutex);
+  CRITICAL_SECTION *impl = mutex->impl;
+
+  if G_UNLIKELY (mutex->impl == NULL)
+    {
+      impl = g_rec_mutex_impl_new ();
+      if (InterlockedCompareExchangePointer (&mutex->impl, impl, NULL) != NULL)
+        g_rec_mutex_impl_free (impl);
+      impl = mutex->impl;
+    }
+
+  return impl;
 }
 
-static gboolean
-g_mutex_trylock_win32_impl (GMutex * mutex)
+void
+g_rec_mutex_init (GRecMutex *mutex)
 {
-  return TryEnterCriticalSection (*(CRITICAL_SECTION **)mutex);
+  mutex->impl = g_rec_mutex_impl_new ();
 }
 
-static void
-g_mutex_unlock_win32_impl (GMutex *mutex)
+void
+g_rec_mutex_clear (GRecMutex *mutex)
 {
-  LeaveCriticalSection (*(CRITICAL_SECTION **)mutex);
+  if (mutex->impl)
+    g_rec_mutex_impl_free (mutex->impl);
 }
 
-static GCond *
-g_cond_new_win32_impl (void)
+void
+g_rec_mutex_lock (GRecMutex *mutex)
 {
-  GCond *retval = g_new (GCond, 1);
-
-  retval->array = g_ptr_array_new ();
-  InitializeCriticalSection (&retval->lock);
+  EnterCriticalSection (g_rec_mutex_get_impl (mutex));
+}
 
-  return retval;
+void
+g_rec_mutex_unlock (GRecMutex *mutex)
+{
+  LeaveCriticalSection (mutex->impl);
 }
 
-static void
-g_cond_signal_win32_impl (GCond * cond)
+gboolean
+g_rec_mutex_trylock (GRecMutex *mutex)
 {
-  EnterCriticalSection (&cond->lock);
+  return TryEnterCriticalSection (g_rec_mutex_get_impl (mutex));
+}
 
-  if (cond->array->len > 0)
-    {
-      SetEvent (g_ptr_array_index (cond->array, 0));
-      g_ptr_array_remove_index (cond->array, 0);
-    }
+/* {{{1 GRWLock */
 
-  LeaveCriticalSection (&cond->lock);
+void
+g_rw_lock_init (GRWLock *lock)
+{
+  g_thread_impl_vtable.InitializeSRWLock (lock);
 }
 
-static void
-g_cond_broadcast_win32_impl (GCond * cond)
+void
+g_rw_lock_clear (GRWLock *lock)
 {
-  guint i;
-  EnterCriticalSection (&cond->lock);
-
-  for (i = 0; i < cond->array->len; i++)
-    SetEvent (g_ptr_array_index (cond->array, i));
+  if (g_thread_impl_vtable.DeleteSRWLock != NULL)
+    g_thread_impl_vtable.DeleteSRWLock (lock);
+}
 
-  g_ptr_array_set_size (cond->array, 0);
-  LeaveCriticalSection (&cond->lock);
+void
+g_rw_lock_writer_lock (GRWLock *lock)
+{
+  g_thread_impl_vtable.AcquireSRWLockExclusive (lock);
 }
 
-static gboolean
-g_cond_wait_internal (GCond *cond,
-                     GMutex *entered_mutex,
-                     gulong milliseconds)
+gboolean
+g_rw_lock_writer_trylock (GRWLock *lock)
 {
-  gulong retval;
-  HANDLE event = TlsGetValue (g_cond_event_tls);
+  return g_thread_impl_vtable.TryAcquireSRWLockExclusive (lock);
+}
 
-  if (!event)
-    {
-      win32_check_for_error (event = CreateEvent (0, FALSE, FALSE, NULL));
-      TlsSetValue (g_cond_event_tls, event);
-    }
+void
+g_rw_lock_writer_unlock (GRWLock *lock)
+{
+  g_thread_impl_vtable.ReleaseSRWLockExclusive (lock);
+}
 
-  EnterCriticalSection (&cond->lock);
+void
+g_rw_lock_reader_lock (GRWLock *lock)
+{
+  g_thread_impl_vtable.AcquireSRWLockShared (lock);
+}
 
-  /* The event must not be signaled. Check this */
-  g_assert (WaitForSingleObject (event, 0) == WAIT_TIMEOUT);
+gboolean
+g_rw_lock_reader_trylock (GRWLock *lock)
+{
+  return g_thread_impl_vtable.TryAcquireSRWLockShared (lock);
+}
 
-  g_ptr_array_add (cond->array, event);
-  LeaveCriticalSection (&cond->lock);
+void
+g_rw_lock_reader_unlock (GRWLock *lock)
+{
+  g_thread_impl_vtable.ReleaseSRWLockShared (lock);
+}
 
-  g_mutex_unlock (entered_mutex);
+/* {{{1 GCond */
+void
+g_cond_init (GCond *cond)
+{
+  g_thread_impl_vtable.InitializeConditionVariable (cond);
+}
 
-  win32_check_for_error (WAIT_FAILED !=
-                        (retval = WaitForSingleObject (event, milliseconds)));
+void
+g_cond_clear (GCond *cond)
+{
+  if (g_thread_impl_vtable.DeleteConditionVariable)
+    g_thread_impl_vtable.DeleteConditionVariable (cond);
+}
 
-  g_mutex_lock (entered_mutex);
+void
+g_cond_signal (GCond *cond)
+{
+  g_thread_impl_vtable.WakeConditionVariable (cond);
+}
 
-  if (retval == WAIT_TIMEOUT)
-    {
-      EnterCriticalSection (&cond->lock);
-      g_ptr_array_remove (cond->array, event);
+void
+g_cond_broadcast (GCond *cond)
+{
+  g_thread_impl_vtable.WakeAllConditionVariable (cond);
+}
 
-      /* In the meantime we could have been signaled, so we must again
-       * wait for the signal, this time with no timeout, to reset
-       * it. retval is set again to honour the late arrival of the
-       * signal */
-      win32_check_for_error (WAIT_FAILED !=
-                            (retval = WaitForSingleObject (event, 0)));
+void
+g_cond_wait (GCond  *cond,
+             GMutex *entered_mutex)
+{
+  g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, INFINITE, 0);
+}
 
-      LeaveCriticalSection (&cond->lock);
-    }
+gboolean
+g_cond_timedwait (GCond  *cond,
+                  GMutex *entered_mutex,
+                  gint64  abs_time)
+{
+  gint64 span;
+  FILETIME ft;
+  gint64 now;
 
-#ifndef G_DISABLE_ASSERT
-  EnterCriticalSection (&cond->lock);
+  GetSystemTimeAsFileTime (&ft);
+  memmove (&now, &ft, sizeof (FILETIME));
 
-  /* Now event must not be inside the array, check this */
-  g_assert (g_ptr_array_remove (cond->array, event) == FALSE);
+  now -= G_GINT64_CONSTANT (116444736000000000);
+  now /= 10;
 
-  LeaveCriticalSection (&cond->lock);
-#endif /* !G_DISABLE_ASSERT */
+  span = abs_time - now;
 
-  return retval != WAIT_TIMEOUT;
-}
+  if G_UNLIKELY (span < 0)
+    span = 0;
 
-static void
-g_cond_wait_win32_impl (GCond *cond,
-                       GMutex *entered_mutex)
-{
-  g_return_if_fail (cond != NULL);
-  g_return_if_fail (entered_mutex != NULL);
+  if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * G_MAXINT32)
+    span = INFINITE;
 
-  g_cond_wait_internal (cond, entered_mutex, INFINITE);
+  return g_thread_impl_vtable.SleepConditionVariableSRW (cond, entered_mutex, span / 1000, 0);
 }
 
-static gboolean
-g_cond_timed_wait_win32_impl (GCond *cond,
-                             GMutex *entered_mutex,
-                             GTimeVal *abs_time)
+gboolean
+g_cond_timed_wait (GCond    *cond,
+                   GMutex   *entered_mutex,
+                   GTimeVal *abs_time)
 {
-  GTimeVal current_time;
-  gulong to_wait;
+  if (abs_time)
+    {
+      gint64 micros;
 
-  g_return_val_if_fail (cond != NULL, FALSE);
-  g_return_val_if_fail (entered_mutex != NULL, FALSE);
+      micros = abs_time->tv_sec;
+      micros *= 1000000;
+      micros += abs_time->tv_usec;
 
-  if (!abs_time)
-    to_wait = INFINITE;
+      return g_cond_timedwait (cond, entered_mutex, micros);
+    }
   else
     {
-      g_get_current_time (&current_time);
-      if (abs_time->tv_sec < current_time.tv_sec ||
-         (abs_time->tv_sec == current_time.tv_sec &&
-          abs_time->tv_usec <= current_time.tv_usec))
-       to_wait = 0;
-      else
-       to_wait = (abs_time->tv_sec - current_time.tv_sec) * 1000 +
-         (abs_time->tv_usec - current_time.tv_usec) / 1000;
+      g_cond_wait (cond, entered_mutex);
+      return TRUE;
     }
-
-  return g_cond_wait_internal (cond, entered_mutex, to_wait);
 }
 
-static void
-g_cond_free_win32_impl (GCond * cond)
-{
-  DeleteCriticalSection (&cond->lock);
-  g_ptr_array_free (cond->array, TRUE);
-  g_free (cond);
-}
+/* {{{1 GPrivate */
 
-static GPrivate *
-g_private_new_win32_impl (GDestroyNotify destructor)
-{
-  GPrivate *result;
-  EnterCriticalSection (&g_thread_global_spinlock);
-  if (g_private_next >= G_PRIVATE_MAX)
-    {
-      char buf[100];
-      sprintf (buf,
-              "Too many GPrivate allocated. Their number is limited to %d.",
-              G_PRIVATE_MAX);
-      MessageBox (NULL, buf, NULL, MB_ICONERROR|MB_SETFOREGROUND);
-      if (IsDebuggerPresent ())
-       G_BREAKPOINT ();
-      abort ();
-    }
-  g_private_destructors[g_private_next] = destructor;
-  result = GUINT_TO_POINTER (g_private_next);
-  g_private_next++;
-  LeaveCriticalSection (&g_thread_global_spinlock);
+typedef struct _GPrivateDestructor GPrivateDestructor;
 
-  return result;
-}
+struct _GPrivateDestructor
+{
+  DWORD               index;
+  GDestroyNotify      notify;
+  GPrivateDestructor *next;
+};
 
-/* NOTE: the functions g_private_get and g_private_set may not use
-   functions from gmem.c and gmessages.c */
+static GPrivateDestructor * volatile g_private_destructors;
 
-static void
-g_private_set_win32_impl (GPrivate * private_key, gpointer value)
+void
+g_private_init (GPrivate       *key,
+                GDestroyNotify  notify)
 {
-  gpointer* array = TlsGetValue (g_private_tls);
-  guint index = GPOINTER_TO_UINT (private_key);
+  GPrivateDestructor *destructor;
 
-  if (index >= G_PRIVATE_MAX)
-      return;
+  key->index = TlsAlloc ();
 
-  if (!array)
-    {
-      array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
-      TlsSetValue (g_private_tls, array);
-    }
+  destructor = malloc (sizeof (GPrivateDestructor));
+  if G_UNLIKELY (destructor == NULL)
+    g_thread_abort (errno, "malloc");
+  destructor->index = key->index;
+  destructor->notify = notify;
+
+  do
+    destructor->next = g_private_destructors;
+  while (InterlockedCompareExchangePointer (&g_private_destructors, destructor->next, destructor) != destructor->next);
 
-  array[index] = value;
+  key->ready = TRUE;
 }
 
-static gpointer
-g_private_get_win32_impl (GPrivate * private_key)
+gpointer
+g_private_get (GPrivate *key)
 {
-  gpointer* array = TlsGetValue (g_private_tls);
-  guint index = GPOINTER_TO_UINT (private_key);
-
-  if (index >= G_PRIVATE_MAX || !array)
-    return NULL;
+  if (!key->ready)
+    return key->single_value;
 
-  return array[index];
+  return TlsGetValue (key->index);
 }
 
-static void
-g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
+void
+g_private_set (GPrivate *key,
+               gpointer  value)
 {
-  GThreadData *target = *(GThreadData **)thread;
-  gint native_prio;
-
-  switch (priority)
+  if (!key->ready)
     {
-    case G_THREAD_PRIORITY_LOW:
-      native_prio = THREAD_PRIORITY_BELOW_NORMAL;
-      break;
+      key->single_value = value;
+      return;
+    }
 
-    case G_THREAD_PRIORITY_NORMAL:
-      native_prio = THREAD_PRIORITY_NORMAL;
-      break;
+  TlsSetValue (key->index, value);
+}
 
-    case G_THREAD_PRIORITY_HIGH:
-      native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
-      break;
+/* {{{1 GThread */
 
-    case G_THREAD_PRIORITY_URGENT:
-      native_prio = THREAD_PRIORITY_HIGHEST;
-      break;
+#include "glib.h"
+#include "gthreadprivate.h"
 
-    default:
-      g_return_if_reached ();
-    }
+#define win32_check_for_error(what) G_STMT_START{                      \
+  if (!(what))                                                         \
+    g_error ("file %s: line %d (%s): error %s during %s",              \
+            __FILE__, __LINE__, G_STRFUNC,                             \
+            g_win32_error_message (GetLastError ()), #what);           \
+  }G_STMT_END
 
-  win32_check_for_error (SetThreadPriority (target->thread, native_prio));
-}
+#define G_MUTEX_SIZE (sizeof (gpointer))
 
-static void
-g_thread_self_win32_impl (gpointer thread)
+static DWORD g_thread_self_tls;
+static DWORD g_private_tls;
+
+typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
+
+typedef struct _GThreadData GThreadData;
+struct _GThreadData
+{
+  GThreadFunc func;
+  gpointer data;
+  HANDLE thread;
+  gboolean joinable;
+};
+
+void
+g_system_thread_self (gpointer thread)
 {
   GThreadData *self = TlsGetValue (g_thread_self_tls);
 
@@ -379,43 +461,40 @@ g_thread_self_win32_impl (gpointer thread)
   *(GThreadData **)thread = self;
 }
 
-static void
-g_thread_exit_win32_impl (void)
+void
+g_system_thread_exit (void)
 {
   GThreadData *self = TlsGetValue (g_thread_self_tls);
-  guint i, private_max;
-  gpointer *array = TlsGetValue (g_private_tls);
-  HANDLE event = TlsGetValue (g_cond_event_tls);
+  gboolean dtors_called;
 
-  EnterCriticalSection (&g_thread_global_spinlock);
-  private_max = g_private_next;
-  LeaveCriticalSection (&g_thread_global_spinlock);
-
-  if (array)
+  do
     {
-      gboolean some_data_non_null;
-
-      do {
-       some_data_non_null = FALSE;
-       for (i = 0; i < private_max; i++)
-         {
-           GDestroyNotify destructor = g_private_destructors[i];
-           GDestroyNotify data = array[i];
-
-           if (data)
-             some_data_non_null = TRUE;
-
-           array[i] = NULL;
-
-           if (destructor && data)
-             destructor (data);
-         }
-      } while (some_data_non_null);
-
-      free (array);
-
-      win32_check_for_error (TlsSetValue (g_private_tls, NULL));
+      GPrivateDestructor *dtor;
+
+      /* We go by the POSIX book on this one.
+       *
+       * If we call a destructor then there is a chance that some new
+       * TLS variables got set by code called in that destructor.
+       *
+       * Loop until nothing is left.
+       */
+      dtors_called = FALSE;
+
+      for (dtor = g_private_destructors; dtor; dtor = dtor->next)
+        {
+          gpointer value;
+
+          value = TlsGetValue (dtor->index);
+          if (value != NULL && dtor->notify != NULL)
+            {
+              /* POSIX says to clear this before the call */
+              TlsSetValue (dtor->index, NULL);
+              dtor->notify (value);
+              dtors_called = TRUE;
+            }
+        }
     }
+  while (dtors_called);
 
   if (self)
     {
@@ -427,11 +506,8 @@ g_thread_exit_win32_impl (void)
       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
     }
 
-  if (event)
-    {
-      CloseHandle (event);
-      win32_check_for_error (TlsSetValue (g_cond_event_tls, NULL));
-    }
+  if (g_thread_impl_vtable.CallThisOnThreadExit)
+    g_thread_impl_vtable.CallThisOnThreadExit ();
 
   _endthreadex (0);
 }
@@ -445,29 +521,25 @@ g_thread_proxy (gpointer data)
 
   self->func (self->data);
 
-  g_thread_exit_win32_impl ();
+  g_system_thread_exit ();
 
   g_assert_not_reached ();
 
   return 0;
 }
 
-static void
-g_thread_create_win32_impl (GThreadFunc func,
-                           gpointer data,
-                           gulong stack_size,
-                           gboolean joinable,
-                           gboolean bound,
-                           GThreadPriority priority,
-                           gpointer thread,
-                           GError **error)
+void
+g_system_thread_create (GThreadFunc       func,
+                        gpointer          data,
+                        gulong            stack_size,
+                        gboolean          joinable,
+                        gpointer          thread,
+                        GError          **error)
 {
   guint ignore;
   GThreadData *retval;
 
   g_return_if_fail (func);
-  g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
-  g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
 
   retval = g_new(GThreadData, 1);
   retval->func = func;
@@ -489,18 +561,16 @@ g_thread_create_win32_impl (GThreadFunc func,
     }
 
   *(GThreadData **)thread = retval;
-
-  g_thread_set_priority_win32_impl (thread, priority);
 }
 
-static void
-g_thread_yield_win32_impl (void)
+void
+g_thread_yield (void)
 {
   Sleep(0);
 }
 
-static void
-g_thread_join_win32_impl (gpointer thread)
+void
+g_system_thread_join (gpointer thread)
 {
   GThreadData *target = *(GThreadData **)thread;
 
@@ -513,46 +583,445 @@ g_thread_join_win32_impl (gpointer thread)
   g_free (target);
 }
 
-GThreadFunctions g_thread_functions_for_glib_use =
-{
-  g_mutex_new_win32_impl,           /* mutex */
-  g_mutex_lock_win32_impl,
-  g_mutex_trylock_win32_impl,
-  g_mutex_unlock_win32_impl,
-  g_mutex_free_win32_impl,
-  g_cond_new_win32_impl,            /* condition */
-  g_cond_signal_win32_impl,
-  g_cond_broadcast_win32_impl,
-  g_cond_wait_win32_impl,
-  g_cond_timed_wait_win32_impl,
-  g_cond_free_win32_impl,
-  g_private_new_win32_impl,         /* private thread data */
-  g_private_get_win32_impl,
-  g_private_set_win32_impl,
-  g_thread_create_win32_impl,       /* thread */
-  g_thread_yield_win32_impl,
-  g_thread_join_win32_impl,
-  g_thread_exit_win32_impl,
-  g_thread_set_priority_win32_impl,
-  g_thread_self_win32_impl,
-  NULL                             /* no equal function necessary */
+gboolean
+g_system_thread_equal (gpointer thread1,
+                       gpointer thread2)
+{
+   return ((GSystemThread*)thread1)->dummy_pointer == ((GSystemThread*)thread2)->dummy_pointer;
+}
+
+/* {{{1 SRWLock and CONDITION_VARIABLE emulation (for Windows XP) */
+
+static CRITICAL_SECTION g_thread_xp_lock;
+static DWORD            g_thread_xp_waiter_tls;
+
+/* {{{2 GThreadWaiter utility class for CONDITION_VARIABLE emulation */
+typedef struct _GThreadXpWaiter GThreadXpWaiter;
+struct _GThreadXpWaiter
+{
+  HANDLE                    event;
+  volatile GThreadXpWaiter *next;
 };
 
-void
-_g_thread_impl_init (void)
+static GThreadXpWaiter *
+g_thread_xp_waiter_get (void)
 {
-  static gboolean beenhere = FALSE;
+  GThreadXpWaiter *waiter;
 
-  if (beenhere)
-    return;
+  waiter = TlsGetValue (g_thread_xp_waiter_tls);
 
-  beenhere = TRUE;
+  if G_UNLIKELY (waiter == NULL)
+    {
+      waiter = malloc (sizeof (GThreadXpWaiter));
+      if (waiter == NULL)
+        g_thread_abort (GetLastError (), "malloc");
+      waiter->event = CreateEvent (0, FALSE, FALSE, NULL);
+      if (waiter->event == NULL)
+        g_thread_abort (GetLastError (), "CreateEvent");
+
+      TlsSetValue (g_thread_xp_waiter_tls, waiter);
+    }
 
-  win32_check_for_error (TLS_OUT_OF_INDEXES !=
-                        (g_thread_self_tls = TlsAlloc ()));
-  win32_check_for_error (TLS_OUT_OF_INDEXES !=
-                        (g_private_tls = TlsAlloc ()));
-  win32_check_for_error (TLS_OUT_OF_INDEXES !=
-                        (g_cond_event_tls = TlsAlloc ()));
-  InitializeCriticalSection (&g_thread_global_spinlock);
+  return waiter;
 }
+
+static void __stdcall
+g_thread_xp_CallThisOnThreadExit (void)
+{
+  GThreadXpWaiter *waiter;
+
+  waiter = TlsGetValue (g_thread_xp_waiter_tls);
+
+  if (waiter != NULL)
+    {
+      TlsSetValue (g_thread_xp_waiter_tls, NULL);
+      CloseHandle (waiter->event);
+      free (waiter);
+    }
+}
+
+/* {{{2 SRWLock emulation */
+typedef struct
+{
+  CRITICAL_SECTION  writer_lock;
+  gboolean          ever_shared;    /* protected by writer_lock */
+
+  /* below is only ever touched if ever_shared becomes true */
+  CRITICAL_SECTION  atomicity;
+  GThreadXpWaiter  *queued_writer; /* protected by atomicity lock */
+  gint              num_readers;   /* protected by atomicity lock */
+} GThreadSRWLock;
+
+static void __stdcall
+g_thread_xp_InitializeSRWLock (gpointer mutex)
+{
+  *(GThreadSRWLock * volatile *) mutex = NULL;
+}
+
+static void __stdcall
+g_thread_xp_DeleteSRWLock (gpointer mutex)
+{
+  GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
+
+  if (lock)
+    {
+      if (lock->ever_shared)
+        DeleteCriticalSection (&lock->atomicity);
+
+      DeleteCriticalSection (&lock->writer_lock);
+      free (lock);
+    }
+}
+
+static GThreadSRWLock * __stdcall
+g_thread_xp_get_srwlock (GThreadSRWLock * volatile *lock)
+{
+  GThreadSRWLock *result;
+
+  /* It looks like we're missing some barriers here, but this code only
+   * ever runs on Windows XP, which in turn only ever runs on hardware
+   * with a relatively rigid memory model.  The 'volatile' will take
+   * care of the compiler.
+   */
+  result = *lock;
+
+  if G_UNLIKELY (result == NULL)
+    {
+      EnterCriticalSection (&g_thread_xp_lock);
+
+      result = malloc (sizeof (GThreadSRWLock));
+
+      if (result == NULL)
+        g_thread_abort (errno, "malloc");
+
+      InitializeCriticalSection (&result->writer_lock);
+      result->ever_shared = FALSE;
+      *lock = result;
+
+      LeaveCriticalSection (&g_thread_xp_lock);
+    }
+
+  return result;
+}
+
+static void __stdcall
+g_thread_xp_AcquireSRWLockExclusive (gpointer mutex)
+{
+  GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
+
+  EnterCriticalSection (&lock->writer_lock);
+
+  if (lock->ever_shared)
+    {
+      GThreadXpWaiter *waiter = NULL;
+
+      EnterCriticalSection (&lock->atomicity);
+      if (lock->num_readers > 0)
+        lock->queued_writer = waiter = g_thread_xp_waiter_get ();
+      LeaveCriticalSection (&lock->atomicity);
+
+      if (waiter != NULL)
+        WaitForSingleObject (waiter->event, INFINITE);
+
+      lock->queued_writer = NULL;
+    }
+}
+
+static BOOLEAN __stdcall
+g_thread_xp_TryAcquireSRWLockExclusive (gpointer mutex)
+{
+  GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
+
+  if (!TryEnterCriticalSection (&lock->writer_lock))
+    return FALSE;
+
+  if (lock->ever_shared)
+    {
+      gboolean available;
+
+      EnterCriticalSection (&lock->atomicity);
+      available = lock->num_readers == 0;
+      LeaveCriticalSection (&lock->atomicity);
+
+      if (!available)
+        {
+          LeaveCriticalSection (&lock->writer_lock);
+          return FALSE;
+        }
+    }
+
+  return TRUE;
+}
+
+static void __stdcall
+g_thread_xp_ReleaseSRWLockExclusive (gpointer mutex)
+{
+  GThreadSRWLock *lock = *(GThreadSRWLock * volatile *) mutex;
+
+  /* We need this until we fix some weird parts of GLib that try to
+   * unlock freshly-allocated mutexes.
+   */
+  if (lock != NULL)
+    LeaveCriticalSection (&lock->writer_lock);
+}
+
+static void
+g_thread_xp_srwlock_become_reader (GThreadSRWLock *lock)
+{
+  if G_UNLIKELY (!lock->ever_shared)
+    {
+      InitializeCriticalSection (&lock->atomicity);
+      lock->queued_writer = NULL;
+      lock->num_readers = 0;
+
+      lock->ever_shared = TRUE;
+    }
+
+  EnterCriticalSection (&lock->atomicity);
+  lock->num_readers++;
+  LeaveCriticalSection (&lock->atomicity);
+}
+
+static void __stdcall
+g_thread_xp_AcquireSRWLockShared (gpointer mutex)
+{
+  GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
+
+  EnterCriticalSection (&lock->writer_lock);
+
+  g_thread_xp_srwlock_become_reader (lock);
+
+  LeaveCriticalSection (&lock->writer_lock);
+}
+
+static BOOLEAN __stdcall
+g_thread_xp_TryAcquireSRWLockShared (gpointer mutex)
+{
+  GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
+
+  if (!TryEnterCriticalSection (&lock->writer_lock))
+    return FALSE;
+
+  g_thread_xp_srwlock_become_reader (lock);
+
+  LeaveCriticalSection (&lock->writer_lock);
+
+  return TRUE;
+}
+
+static void __stdcall
+g_thread_xp_ReleaseSRWLockShared (gpointer mutex)
+{
+  GThreadSRWLock *lock = g_thread_xp_get_srwlock (mutex);
+
+  EnterCriticalSection (&lock->atomicity);
+
+  lock->num_readers--;
+
+  if (lock->num_readers == 0 && lock->queued_writer)
+    SetEvent (lock->queued_writer->event);
+
+  LeaveCriticalSection (&lock->atomicity);
+}
+
+/* {{{2 CONDITION_VARIABLE emulation */
+typedef struct
+{
+  volatile GThreadXpWaiter  *first;
+  volatile GThreadXpWaiter **last_ptr;
+} GThreadXpCONDITION_VARIABLE;
+
+static void __stdcall
+g_thread_xp_InitializeConditionVariable (gpointer cond)
+{
+  *(GThreadXpCONDITION_VARIABLE * volatile *) cond = NULL;
+}
+
+static void __stdcall
+g_thread_xp_DeleteConditionVariable (gpointer cond)
+{
+  GThreadXpCONDITION_VARIABLE *cv = *(GThreadXpCONDITION_VARIABLE * volatile *) cond;
+
+  if (cv)
+    free (cv);
+}
+
+static GThreadXpCONDITION_VARIABLE * __stdcall
+g_thread_xp_get_condition_variable (GThreadXpCONDITION_VARIABLE * volatile *cond)
+{
+  GThreadXpCONDITION_VARIABLE *result;
+
+  /* It looks like we're missing some barriers here, but this code only
+   * ever runs on Windows XP, which in turn only ever runs on hardware
+   * with a relatively rigid memory model.  The 'volatile' will take
+   * care of the compiler.
+   */
+  result = *cond;
+
+  if G_UNLIKELY (result == NULL)
+    {
+      result = malloc (sizeof (GThreadXpCONDITION_VARIABLE));
+
+      if (result == NULL)
+        g_thread_abort (errno, "malloc");
+
+      result->first = NULL;
+      result->last_ptr = &result->first;
+
+      if (InterlockedCompareExchangePointer (cond, result, NULL) != NULL)
+        {
+          free (result);
+          result = *cond;
+        }
+    }
+
+  return result;
+}
+
+static BOOL __stdcall
+g_thread_xp_SleepConditionVariableSRW (gpointer cond,
+                                       gpointer mutex,
+                                       DWORD    timeout,
+                                       ULONG    flags)
+{
+  GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
+  GThreadXpWaiter *waiter = g_thread_xp_waiter_get ();
+  DWORD status;
+
+  waiter->next = NULL;
+
+  EnterCriticalSection (&g_thread_xp_lock);
+  *cv->last_ptr = waiter;
+  cv->last_ptr = &waiter->next;
+  LeaveCriticalSection (&g_thread_xp_lock);
+
+  g_mutex_unlock (mutex);
+  status = WaitForSingleObject (waiter->event, timeout);
+
+  if (status != WAIT_TIMEOUT && status != WAIT_OBJECT_0)
+    g_thread_abort (GetLastError (), "WaitForSingleObject");
+
+  g_mutex_lock (mutex);
+
+  return status == WAIT_OBJECT_0;
+}
+
+static void __stdcall
+g_thread_xp_WakeConditionVariable (gpointer cond)
+{
+  GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
+  volatile GThreadXpWaiter *waiter;
+
+  EnterCriticalSection (&g_thread_xp_lock);
+  waiter = cv->first;
+  if (waiter != NULL)
+    {
+      cv->first = waiter->next;
+      if (cv->first == NULL)
+        cv->last_ptr = &cv->first;
+    }
+  LeaveCriticalSection (&g_thread_xp_lock);
+
+  if (waiter != NULL)
+    SetEvent (waiter->event);
+}
+
+static void __stdcall
+g_thread_xp_WakeAllConditionVariable (gpointer cond)
+{
+  GThreadXpCONDITION_VARIABLE *cv = g_thread_xp_get_condition_variable (cond);
+  volatile GThreadXpWaiter *waiter;
+
+  EnterCriticalSection (&g_thread_xp_lock);
+  waiter = cv->first;
+  cv->first = NULL;
+  cv->last_ptr = &cv->first;
+  LeaveCriticalSection (&g_thread_xp_lock);
+
+  while (waiter != NULL)
+    {
+      volatile GThreadXpWaiter *next;
+
+      next = waiter->next;
+      SetEvent (waiter->event);
+      waiter = next;
+    }
+}
+
+/* {{{2 XP Setup */
+static void
+g_thread_xp_init (void)
+{
+  static const GThreadImplVtable g_thread_xp_impl_vtable = {
+    g_thread_xp_CallThisOnThreadExit,
+    g_thread_xp_InitializeSRWLock,
+    g_thread_xp_DeleteSRWLock,
+    g_thread_xp_AcquireSRWLockExclusive,
+    g_thread_xp_TryAcquireSRWLockExclusive,
+    g_thread_xp_ReleaseSRWLockExclusive,
+    g_thread_xp_AcquireSRWLockShared,
+    g_thread_xp_TryAcquireSRWLockShared,
+    g_thread_xp_ReleaseSRWLockShared,
+    g_thread_xp_InitializeConditionVariable,
+    g_thread_xp_DeleteConditionVariable,
+    g_thread_xp_SleepConditionVariableSRW,
+    g_thread_xp_WakeAllConditionVariable,
+    g_thread_xp_WakeConditionVariable
+  };
+
+  InitializeCriticalSection (&g_thread_xp_lock);
+  g_thread_xp_waiter_tls = TlsAlloc ();
+
+  g_thread_impl_vtable = g_thread_xp_impl_vtable;
+}
+
+/* {{{1 Epilogue */
+
+static gboolean
+g_thread_lookup_native_funcs (void)
+{
+  GThreadImplVtable native_vtable = { 0, };
+  HMODULE kernel32;
+
+  kernel32 = GetModuleHandle ("KERNEL32.DLL");
+
+  if (kernel32 == NULL)
+    return FALSE;
+
+#define GET_FUNC(name) if ((native_vtable.name = (void *) GetProcAddress (kernel32, #name)) == NULL) return FALSE
+  GET_FUNC(InitializeSRWLock);
+  GET_FUNC(AcquireSRWLockExclusive);
+  GET_FUNC(TryAcquireSRWLockExclusive);
+  GET_FUNC(ReleaseSRWLockExclusive);
+  GET_FUNC(AcquireSRWLockShared);
+  GET_FUNC(TryAcquireSRWLockShared);
+  GET_FUNC(ReleaseSRWLockShared);
+
+  GET_FUNC(InitializeConditionVariable);
+  GET_FUNC(SleepConditionVariableSRW);
+  GET_FUNC(WakeAllConditionVariable);
+  GET_FUNC(WakeConditionVariable);
+#undef GET_FUNC
+
+  g_thread_impl_vtable = native_vtable;
+
+  return TRUE;
+}
+
+G_GNUC_INTERNAL void
+g_thread_DllMain (void)
+{
+  if (g_thread_lookup_native_funcs ())
+    fprintf (stderr, "(debug) GThread using native mode\n");
+  else
+    {
+      fprintf (stderr, "(debug) GThread using Windows XP mode\n");
+      g_thread_xp_init ();
+    }
+
+  win32_check_for_error (TLS_OUT_OF_INDEXES != (g_thread_self_tls = TlsAlloc ()));
+  win32_check_for_error (TLS_OUT_OF_INDEXES != (g_private_tls = TlsAlloc ()));
+}
+
+/* vim:set foldmethod=marker: */
+