Imported Upstream version 2.73.3
[platform/upstream/glib.git] / glib / gthread-win32.c
index d50aee1..8010520 100644 (file)
@@ -5,10 +5,12 @@
  * Copyright 1998-2001 Sebastian Wilhelmi; University of Karlsruhe
  * Copyright 2001 Hans Breuer
  *
+ * SPDX-License-Identifier: LGPL-2.1-or-later
+ *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * version 2.1 of the License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -16,9 +18,7 @@
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA 02111-1307, USA.
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
 /*
  * 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 "glib-init.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;
+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);
+  g_abort ();
+}
 
-typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
+/* Starting with Vista and Windows 2008, we have access to the
+ * CONDITION_VARIABLE and SRWLock primitives on Windows, which are
+ * pretty reasonable approximations of the primitives 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.  That means that they are completely ABI compatible with our
+ * GMutex and GCond APIs.
+ */
 
-/* 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
+/* {{{1 GMutex */
+void
+g_mutex_init (GMutex *mutex)
+{
+  InitializeSRWLock ((gpointer) mutex);
+}
 
-static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
+void
+g_mutex_clear (GMutex *mutex)
+{
+}
 
-static guint g_private_next = 0;
+void
+g_mutex_lock (GMutex *mutex)
+{
+  AcquireSRWLockExclusive ((gpointer) mutex);
+}
 
-typedef struct _GThreadData GThreadData;
-struct _GThreadData
+gboolean
+g_mutex_trylock (GMutex *mutex)
 {
-  GThreadFunc func;
-  gpointer data;
-  HANDLE thread;
-  gboolean joinable;
-};
+  return TryAcquireSRWLockExclusive ((gpointer) mutex);
+}
 
-struct _GCond
+void
+g_mutex_unlock (GMutex *mutex)
 {
-  GPtrArray *array;
-  CRITICAL_SECTION lock;
-};
+  ReleaseSRWLockExclusive ((gpointer) 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->p;
+
+  if G_UNLIKELY (mutex->p == NULL)
+    {
+      impl = g_rec_mutex_impl_new ();
+      if (InterlockedCompareExchangePointer (&mutex->p, impl, NULL) != NULL)
+        g_rec_mutex_impl_free (impl);
+      impl = mutex->p;
+    }
+
+  return impl;
 }
 
-static gboolean
-g_mutex_trylock_win32_impl (GMutex * mutex)
+void
+g_rec_mutex_init (GRecMutex *mutex)
 {
-  return TryEnterCriticalSection (*(CRITICAL_SECTION **)mutex);
+  mutex->p = 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);
+  g_rec_mutex_impl_free (mutex->p);
 }
 
-static GCond *
-g_cond_new_win32_impl (void)
+void
+g_rec_mutex_lock (GRecMutex *mutex)
 {
-  GCond *retval = g_new (GCond, 1);
+  EnterCriticalSection (g_rec_mutex_get_impl (mutex));
+}
 
-  retval->array = g_ptr_array_new ();
-  InitializeCriticalSection (&retval->lock);
+void
+g_rec_mutex_unlock (GRecMutex *mutex)
+{
+  LeaveCriticalSection (mutex->p);
+}
 
-  return retval;
+gboolean
+g_rec_mutex_trylock (GRecMutex *mutex)
+{
+  return TryEnterCriticalSection (g_rec_mutex_get_impl (mutex));
 }
 
-static void
-g_cond_signal_win32_impl (GCond * cond)
+/* {{{1 GRWLock */
+
+void
+g_rw_lock_init (GRWLock *lock)
 {
-  EnterCriticalSection (&cond->lock);
+  InitializeSRWLock ((gpointer) lock);
+}
 
-  if (cond->array->len > 0)
-    {
-      SetEvent (g_ptr_array_index (cond->array, 0));
-      g_ptr_array_remove_index (cond->array, 0);
-    }
+void
+g_rw_lock_clear (GRWLock *lock)
+{
+}
 
-  LeaveCriticalSection (&cond->lock);
+void
+g_rw_lock_writer_lock (GRWLock *lock)
+{
+  AcquireSRWLockExclusive ((gpointer) lock);
 }
 
-static void
-g_cond_broadcast_win32_impl (GCond * cond)
+gboolean
+g_rw_lock_writer_trylock (GRWLock *lock)
 {
-  guint i;
-  EnterCriticalSection (&cond->lock);
+  return TryAcquireSRWLockExclusive ((gpointer) lock);
+}
 
-  for (i = 0; i < cond->array->len; i++)
-    SetEvent (g_ptr_array_index (cond->array, i));
+void
+g_rw_lock_writer_unlock (GRWLock *lock)
+{
+  ReleaseSRWLockExclusive ((gpointer) lock);
+}
 
-  g_ptr_array_set_size (cond->array, 0);
-  LeaveCriticalSection (&cond->lock);
+void
+g_rw_lock_reader_lock (GRWLock *lock)
+{
+  AcquireSRWLockShared ((gpointer) lock);
 }
 
-static gboolean
-g_cond_wait_internal (GCond *cond,
-                     GMutex *entered_mutex,
-                     gulong milliseconds)
+gboolean
+g_rw_lock_reader_trylock (GRWLock *lock)
 {
-  gulong retval;
-  HANDLE event = TlsGetValue (g_cond_event_tls);
+  return TryAcquireSRWLockShared ((gpointer) lock);
+}
 
-  if (!event)
-    {
-      win32_check_for_error (event = CreateEvent (0, FALSE, FALSE, NULL));
-      TlsSetValue (g_cond_event_tls, event);
-    }
+void
+g_rw_lock_reader_unlock (GRWLock *lock)
+{
+  ReleaseSRWLockShared ((gpointer) lock);
+}
 
-  EnterCriticalSection (&cond->lock);
+/* {{{1 GCond */
+void
+g_cond_init (GCond *cond)
+{
+  InitializeConditionVariable ((gpointer) cond);
+}
 
-  /* The event must not be signaled. Check this */
-  g_assert (WaitForSingleObject (event, 0) == WAIT_TIMEOUT);
+void
+g_cond_clear (GCond *cond)
+{
+}
 
-  g_ptr_array_add (cond->array, event);
-  LeaveCriticalSection (&cond->lock);
+void
+g_cond_signal (GCond *cond)
+{
+  WakeConditionVariable ((gpointer) cond);
+}
 
-  g_mutex_unlock (entered_mutex);
+void
+g_cond_broadcast (GCond *cond)
+{
+  WakeAllConditionVariable ((gpointer) cond);
+}
 
-  win32_check_for_error (WAIT_FAILED !=
-                        (retval = WaitForSingleObject (event, milliseconds)));
+void
+g_cond_wait (GCond  *cond,
+             GMutex *entered_mutex)
+{
+  SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, INFINITE, 0);
+}
 
-  g_mutex_lock (entered_mutex);
+gboolean
+g_cond_wait_until (GCond  *cond,
+                   GMutex *entered_mutex,
+                   gint64  end_time)
+{
+  gint64 span, start_time;
+  DWORD span_millis;
+  gboolean signalled;
 
-  if (retval == WAIT_TIMEOUT)
+  start_time = g_get_monotonic_time ();
+  do
     {
-      EnterCriticalSection (&cond->lock);
-      g_ptr_array_remove (cond->array, event);
-
-      /* 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)));
+      span = end_time - start_time;
 
-      LeaveCriticalSection (&cond->lock);
-    }
+      if G_UNLIKELY (span < 0)
+        span_millis = 0;
+      else if G_UNLIKELY (span > G_GINT64_CONSTANT (1000) * (DWORD) INFINITE)
+        span_millis = INFINITE;
+      else
+        /* Round up so we don't time out too early */
+        span_millis = (span + 1000 - 1) / 1000;
 
-#ifndef G_DISABLE_ASSERT
-  EnterCriticalSection (&cond->lock);
+      /* We never want to wait infinitely */
+      if (span_millis >= INFINITE)
+        span_millis = INFINITE - 1;
 
-  /* Now event must not be inside the array, check this */
-  g_assert (g_ptr_array_remove (cond->array, event) == FALSE);
+      signalled = SleepConditionVariableSRW ((gpointer) cond, (gpointer) entered_mutex, span_millis, 0);
+      if (signalled)
+        break;
 
-  LeaveCriticalSection (&cond->lock);
-#endif /* !G_DISABLE_ASSERT */
+      /* In case we didn't wait long enough after a timeout, wait again for the
+       * remaining time */
+      start_time = g_get_monotonic_time ();
+    }
+  while (start_time < end_time);
 
-  return retval != WAIT_TIMEOUT;
+  return signalled;
 }
 
-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);
+/* {{{1 GPrivate */
 
-  g_cond_wait_internal (cond, entered_mutex, INFINITE);
-}
+typedef struct _GPrivateDestructor GPrivateDestructor;
 
-static gboolean
-g_cond_timed_wait_win32_impl (GCond *cond,
-                             GMutex *entered_mutex,
-                             GTimeVal *abs_time)
+struct _GPrivateDestructor
 {
-  GTimeVal current_time;
-  gulong to_wait;
+  DWORD               index;
+  GDestroyNotify      notify;
+  GPrivateDestructor *next;
+};
 
-  g_return_val_if_fail (cond != NULL, FALSE);
-  g_return_val_if_fail (entered_mutex != NULL, FALSE);
+static GPrivateDestructor *g_private_destructors;  /* (atomic) prepend-only */
+static CRITICAL_SECTION g_private_lock;
 
-  if (!abs_time)
-    to_wait = INFINITE;
-  else
+static DWORD
+g_private_get_impl (GPrivate *key)
+{
+  DWORD impl = (DWORD) GPOINTER_TO_UINT(key->p);
+
+  if G_UNLIKELY (impl == 0)
     {
-      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;
+      EnterCriticalSection (&g_private_lock);
+      impl = (UINT_PTR) key->p;
+      if (impl == 0)
+        {
+          GPrivateDestructor *destructor;
+
+          impl = TlsAlloc ();
+
+          if G_UNLIKELY (impl == 0)
+            {
+              /* Ignore TLS index 0 temporarily (as 0 is the indicator that we
+               * haven't allocated TLS yet) and alloc again;
+               * See https://gitlab.gnome.org/GNOME/glib/-/issues/2058 */
+              DWORD impl2 = TlsAlloc ();
+              TlsFree (impl);
+              impl = impl2;
+            }
+
+          if (impl == TLS_OUT_OF_INDEXES || impl == 0)
+            g_thread_abort (0, "TlsAlloc");
+
+          if (key->notify != NULL)
+            {
+              destructor = malloc (sizeof (GPrivateDestructor));
+              if G_UNLIKELY (destructor == NULL)
+                g_thread_abort (errno, "malloc");
+              destructor->index = impl;
+              destructor->notify = key->notify;
+              destructor->next = g_atomic_pointer_get (&g_private_destructors);
+
+              /* We need to do an atomic store due to the unlocked
+               * access to the destructor list from the thread exit
+               * function.
+               *
+               * It can double as a sanity check...
+               */
+              if (!g_atomic_pointer_compare_and_exchange (&g_private_destructors,
+                                                          destructor->next,
+                                                          destructor))
+                g_thread_abort (0, "g_private_get_impl(1)");
+            }
+
+          /* Ditto, due to the unlocked access on the fast path */
+          if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
+            g_thread_abort (0, "g_private_get_impl(2)");
+        }
+      LeaveCriticalSection (&g_private_lock);
     }
 
-  return g_cond_wait_internal (cond, entered_mutex, to_wait);
+  return impl;
 }
 
-static void
-g_cond_free_win32_impl (GCond * cond)
+gpointer
+g_private_get (GPrivate *key)
 {
-  DeleteCriticalSection (&cond->lock);
-  g_ptr_array_free (cond->array, TRUE);
-  g_free (cond);
+  return TlsGetValue (g_private_get_impl (key));
 }
 
-static GPrivate *
-g_private_new_win32_impl (GDestroyNotify destructor)
+void
+g_private_set (GPrivate *key,
+               gpointer  value)
 {
-  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);
-
-  return result;
+  TlsSetValue (g_private_get_impl (key), value);
 }
 
-/* NOTE: the functions g_private_get and g_private_set may not use
-   functions from gmem.c and gmessages.c */
-
-static void
-g_private_set_win32_impl (GPrivate * private_key, gpointer value)
+void
+g_private_replace (GPrivate *key,
+                   gpointer  value)
 {
-  gpointer* array = TlsGetValue (g_private_tls);
-  guint index = GPOINTER_TO_UINT (private_key);
+  DWORD impl = g_private_get_impl (key);
+  gpointer old;
 
-  if (index >= G_PRIVATE_MAX)
-      return;
+  old = TlsGetValue (impl);
+  TlsSetValue (impl, value);
+  if (old && key->notify)
+    key->notify (old);
+}
 
-  if (!array)
-    {
-      array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
-      TlsSetValue (g_private_tls, array);
-    }
+/* {{{1 GThread */
 
-  array[index] = value;
-}
+#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 gpointer
-g_private_get_win32_impl (GPrivate * private_key)
+typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
+
+typedef struct
 {
-  gpointer* array = TlsGetValue (g_private_tls);
-  guint index = GPOINTER_TO_UINT (private_key);
+  GRealThread thread;
 
-  if (index >= G_PRIVATE_MAX || !array)
-    return NULL;
+  GThreadFunc proxy;
+  HANDLE      handle;
+} GThreadWin32;
 
-  return array[index];
+void
+g_system_thread_free (GRealThread *thread)
+{
+  GThreadWin32 *wt = (GThreadWin32 *) thread;
+
+  win32_check_for_error (CloseHandle (wt->handle));
+  g_slice_free (GThreadWin32, wt);
 }
 
-static void
-g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
+void
+g_system_thread_exit (void)
 {
-  GThreadData *target = *(GThreadData **)thread;
-  gint native_prio;
+  /* In static compilation, DllMain doesn't exist and so DLL_THREAD_DETACH
+   * case is never called and thread destroy notifications are not triggered.
+   * To ensure that notifications are correctly triggered in static
+   * compilation mode, we call directly the "detach" function here right
+   * before terminating the thread.
+   * As all win32 threads initialized through the glib API are run through
+   * the same proxy function g_thread_win32_proxy() which calls systematically
+   * g_system_thread_exit() when finishing, we obtain the same behavior as
+   * with dynamic compilation.
+   *
+   * WARNING: unfortunately this mechanism cannot work with threads created
+   * directly from the Windows API using CreateThread() or _beginthread/ex().
+   * It only works with threads created by using the glib API with
+   * g_system_thread_new(). If users need absolutely to use a thread NOT
+   * created with glib API under Windows and in static compilation mode, they
+   * should not use glib functions within their thread or they may encounter
+   * memory leaks when the thread finishes.
+   */
+#ifdef GLIB_STATIC_COMPILATION
+  g_thread_win32_thread_detach ();
+#endif
 
-  switch (priority)
-    {
-    case G_THREAD_PRIORITY_LOW:
-      native_prio = THREAD_PRIORITY_BELOW_NORMAL;
-      break;
+  _endthreadex (0);
+}
 
-    case G_THREAD_PRIORITY_NORMAL:
-      native_prio = THREAD_PRIORITY_NORMAL;
-      break;
+static guint __stdcall
+g_thread_win32_proxy (gpointer data)
+{
+  GThreadWin32 *self = data;
 
-    case G_THREAD_PRIORITY_HIGH:
-      native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
-      break;
+  self->proxy (self);
 
-    case G_THREAD_PRIORITY_URGENT:
-      native_prio = THREAD_PRIORITY_HIGHEST;
-      break;
+  g_system_thread_exit ();
 
-    default:
-      g_return_if_reached ();
-    }
+  g_assert_not_reached ();
 
-  win32_check_for_error (SetThreadPriority (target->thread, native_prio));
+  return 0;
 }
 
-static void
-g_thread_self_win32_impl (gpointer thread)
+gboolean
+g_system_thread_get_scheduler_settings (GThreadSchedulerSettings *scheduler_settings)
 {
-  GThreadData *self = TlsGetValue (g_thread_self_tls);
-
-  if (!self)
-    {
-      /* This should only happen for the main thread! */
-      HANDLE handle = GetCurrentThread ();
-      HANDLE process = GetCurrentProcess ();
-      self = g_new (GThreadData, 1);
-      win32_check_for_error (DuplicateHandle (process, handle, process,
-                                             &self->thread, 0, FALSE,
-                                             DUPLICATE_SAME_ACCESS));
-      win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
-      self->func = NULL;
-      self->data = NULL;
-      self->joinable = FALSE;
-    }
+  HANDLE current_thread = GetCurrentThread ();
+  scheduler_settings->thread_prio = GetThreadPriority (current_thread);
 
-  *(GThreadData **)thread = self;
+  return TRUE;
 }
 
-static void
-g_thread_exit_win32_impl (void)
+GRealThread *
+g_system_thread_new (GThreadFunc proxy,
+                     gulong stack_size,
+                     const GThreadSchedulerSettings *scheduler_settings,
+                     const char *name,
+                     GThreadFunc func,
+                     gpointer data,
+                     GError **error)
 {
-  GThreadData *self = TlsGetValue (g_thread_self_tls);
-  guint i, private_max;
-  gpointer *array = TlsGetValue (g_private_tls);
-  HANDLE event = TlsGetValue (g_cond_event_tls);
-
-  EnterCriticalSection (&g_thread_global_spinlock);
-  private_max = g_private_next;
-  LeaveCriticalSection (&g_thread_global_spinlock);
-
-  if (array)
+  GThreadWin32 *thread;
+  GRealThread *base_thread;
+  guint ignore;
+  const gchar *message = NULL;
+  int thread_prio;
+
+  thread = g_slice_new0 (GThreadWin32);
+  thread->proxy = proxy;
+  thread->handle = (HANDLE) NULL;
+  base_thread = (GRealThread*)thread;
+  base_thread->ref_count = 2;
+  base_thread->ours = TRUE;
+  base_thread->thread.joinable = TRUE;
+  base_thread->thread.func = func;
+  base_thread->thread.data = data;
+  base_thread->name = g_strdup (name);
+
+  thread->handle = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_win32_proxy, thread,
+                                            CREATE_SUSPENDED, &ignore);
+
+  if (thread->handle == NULL)
     {
-      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;
+      message = "Error creating thread";
+      goto error;
+    }
 
-           if (destructor && data)
-             destructor (data);
-         }
-      } while (some_data_non_null);
+  /* For thread priority inheritance we need to manually set the thread
+   * priority of the new thread to the priority of the current thread. We
+   * also have to start the thread suspended and resume it after actually
+   * setting the priority here.
+   *
+   * On Windows, by default all new threads are created with NORMAL thread
+   * priority.
+   */
 
-      free (array);
+  if (scheduler_settings)
+    {
+      thread_prio = scheduler_settings->thread_prio;
+    }
+  else
+    {
+      HANDLE current_thread = GetCurrentThread ();
+      thread_prio = GetThreadPriority (current_thread);
+    }
 
-      win32_check_for_error (TlsSetValue (g_private_tls, NULL));
+  if (thread_prio == THREAD_PRIORITY_ERROR_RETURN)
+    {
+      message = "Error getting current thread priority";
+      goto error;
     }
 
-  if (self)
+  if (SetThreadPriority (thread->handle, thread_prio) == 0)
     {
-      if (!self->joinable)
-       {
-         win32_check_for_error (CloseHandle (self->thread));
-         g_free (self);
-       }
-      win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
+      message = "Error setting new thread priority";
+      goto error;
     }
 
-  if (event)
+  if (ResumeThread (thread->handle) == (DWORD) -1)
     {
-      CloseHandle (event);
-      win32_check_for_error (TlsSetValue (g_cond_event_tls, NULL));
+      message = "Error resuming new thread";
+      goto error;
     }
 
-  _endthreadex (0);
+  return (GRealThread *) thread;
+
+error:
+  {
+    gchar *win_error = g_win32_error_message (GetLastError ());
+    g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
+                 "%s: %s", message, win_error);
+    g_free (win_error);
+    if (thread->handle)
+      CloseHandle (thread->handle);
+    g_slice_free (GThreadWin32, thread);
+    return NULL;
+  }
 }
 
-static guint __stdcall
-g_thread_proxy (gpointer data)
+void
+g_thread_yield (void)
+{
+  Sleep(0);
+}
+
+void
+g_system_thread_wait (GRealThread *thread)
 {
-  GThreadData *self = (GThreadData*) data;
+  GThreadWin32 *wt = (GThreadWin32 *) thread;
 
-  win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
+  win32_check_for_error (WAIT_FAILED != WaitForSingleObject (wt->handle, INFINITE));
+}
 
-  self->func (self->data);
+#define EXCEPTION_SET_THREAD_NAME ((DWORD) 0x406D1388)
 
-  g_thread_exit_win32_impl ();
+#ifndef _MSC_VER
+static void *SetThreadName_VEH_handle = NULL;
 
-  g_assert_not_reached ();
+static LONG __stdcall
+SetThreadName_VEH (PEXCEPTION_POINTERS ExceptionInfo)
+{
+  if (ExceptionInfo->ExceptionRecord != NULL &&
+      ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SET_THREAD_NAME)
+    return EXCEPTION_CONTINUE_EXECUTION;
 
-  return 0;
+  return EXCEPTION_CONTINUE_SEARCH;
 }
+#endif
+
+typedef struct _THREADNAME_INFO
+{
+  DWORD  dwType;       /* must be 0x1000 */
+  LPCSTR szName;       /* pointer to name (in user addr space) */
+  DWORD  dwThreadID;   /* thread ID (-1=caller thread) */
+  DWORD  dwFlags;      /* reserved for future use, must be zero */
+} THREADNAME_INFO;
 
 static void
-g_thread_create_win32_impl (GThreadFunc func,
-                           gpointer data,
-                           gulong stack_size,
-                           gboolean joinable,
-                           gboolean bound,
-                           GThreadPriority priority,
-                           gpointer thread,
-                           GError **error)
+SetThreadName (DWORD  dwThreadID,
+               LPCSTR szThreadName)
 {
-  guint ignore;
-  GThreadData *retval;
+   THREADNAME_INFO info;
+   DWORD infosize;
+
+   info.dwType = 0x1000;
+   info.szName = szThreadName;
+   info.dwThreadID = dwThreadID;
+   info.dwFlags = 0;
+
+   infosize = sizeof (info) / sizeof (DWORD);
+
+#ifdef _MSC_VER
+   __try
+     {
+       RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize,
+                       (const ULONG_PTR *) &info);
+     }
+   __except (EXCEPTION_EXECUTE_HANDLER)
+     {
+     }
+#else
+   /* Without a debugger we *must* have an exception handler,
+    * otherwise raising an exception will crash the process.
+    */
+   if ((!IsDebuggerPresent ()) && (SetThreadName_VEH_handle == NULL))
+     return;
+
+   RaiseException (EXCEPTION_SET_THREAD_NAME, 0, infosize, (const ULONG_PTR *) &info);
+#endif
+}
 
-  g_return_if_fail (func);
-  g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
-  g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
+typedef HRESULT (WINAPI *pSetThreadDescription) (HANDLE hThread,
+                                                 PCWSTR lpThreadDescription);
+static pSetThreadDescription SetThreadDescriptionFunc = NULL;
+static HMODULE kernel32_module = NULL;
 
-  retval = g_new(GThreadData, 1);
-  retval->func = func;
-  retval->data = data;
+static gboolean
+g_thread_win32_load_library (void)
+{
+  /* FIXME: Add support for UWP app */
+#if !defined(G_WINAPI_ONLY_APP)
+  static gsize _init_once = 0;
+  if (g_once_init_enter (&_init_once))
+    {
+      kernel32_module = LoadLibraryW (L"kernel32.dll");
+      if (kernel32_module)
+        {
+          SetThreadDescriptionFunc =
+              (pSetThreadDescription) GetProcAddress (kernel32_module,
+                                                      "SetThreadDescription");
+          if (!SetThreadDescriptionFunc)
+            FreeLibrary (kernel32_module);
+        }
+      g_once_init_leave (&_init_once, 1);
+    }
+#endif
 
-  retval->joinable = joinable;
+  return !!SetThreadDescriptionFunc;
+}
 
-  retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
-                                           retval, 0, &ignore);
+static gboolean
+g_thread_win32_set_thread_desc (const gchar *name)
+{
+  HRESULT hr;
+  wchar_t *namew;
 
-  if (retval->thread == NULL)
-    {
-      gchar *win_error = g_win32_error_message (GetLastError ());
-      g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
-                   "Error creating thread: %s", win_error);
-      g_free (retval);
-      g_free (win_error);
-      return;
-    }
+  if (!g_thread_win32_load_library () || !name)
+    return FALSE;
+
+  namew = g_utf8_to_utf16 (name, -1, NULL, NULL, NULL);
+  if (!namew)
+    return FALSE;
 
-  *(GThreadData **)thread = retval;
+  hr = SetThreadDescriptionFunc (GetCurrentThread (), namew);
 
-  g_thread_set_priority_win32_impl (thread, priority);
+  g_free (namew);
+  return SUCCEEDED (hr);
 }
 
-static void
-g_thread_yield_win32_impl (void)
+void
+g_system_thread_set_name (const gchar *name)
 {
-  Sleep(0);
+  /* Prefer SetThreadDescription over exception based way if available,
+   * since thread description set by SetThreadDescription will be preserved
+   * in dump file */
+  if (!g_thread_win32_set_thread_desc (name))
+    SetThreadName ((DWORD) -1, name);
 }
 
-static void
-g_thread_join_win32_impl (gpointer thread)
-{
-  GThreadData *target = *(GThreadData **)thread;
-
-  g_return_if_fail (target->joinable);
-
-  win32_check_for_error (WAIT_FAILED !=
-                        WaitForSingleObject (target->thread, INFINITE));
-
-  win32_check_for_error (CloseHandle (target->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 */
-};
+/* {{{1 Epilogue */
 
 void
-_g_thread_impl_init (void)
+g_thread_win32_init (void)
 {
-  static gboolean beenhere = FALSE;
+  InitializeCriticalSection (&g_private_lock);
 
-  if (beenhere)
-    return;
+#ifndef _MSC_VER
+  SetThreadName_VEH_handle = AddVectoredExceptionHandler (1, &SetThreadName_VEH);
+  if (SetThreadName_VEH_handle == NULL)
+    {
+      /* This is bad, but what can we do? */
+    }
+#endif
+}
+
+void
+g_thread_win32_thread_detach (void)
+{
+  gboolean dtors_called;
 
-  beenhere = TRUE;
+  do
+    {
+      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_atomic_pointer_get (&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);
+}
 
-  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);
+void
+g_thread_win32_process_detach (void)
+{
+#ifndef _MSC_VER
+  if (SetThreadName_VEH_handle != NULL)
+    {
+      RemoveVectoredExceptionHandler (SetThreadName_VEH_handle);
+      SetThreadName_VEH_handle = NULL;
+    }
+#endif
 }
+
+/* vim:set foldmethod=marker: */