gthread-win32.c 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * gthread.c: solaris thread system implementation
 * Copyright 1998-2001 Sebastian Wilhelmi; University of Karlsruhe
 * Copyright 2001 Hans Breuer
 *
 * 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.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * 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.
 */

/*
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
28
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
29 30
 */

31
/*
32 33 34
 * MT safe
 */

35
#include "config.h"
36

37
#include "glib.h"
38 39

#define STRICT
40
#define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
41 42 43 44
#include <windows.h>
#undef STRICT

#include <process.h>
45
#include <stdlib.h>
46
#include <stdio.h>
47 48 49

#define win32_check_for_error(what) G_STMT_START{			\
  if (!(what))								\
50
    g_error ("file %s: line %d (%s): error %s during %s",		\
51
	     __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION,		\
52
	     g_win32_error_message (GetLastError ()), #what);		\
53 54
  }G_STMT_END

55
#define G_MUTEX_SIZE (sizeof (gpointer))
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

#define PRIORITY_LOW_VALUE    THREAD_PRIORITY_BELOW_NORMAL
#define PRIORITY_NORMAL_VALUE THREAD_PRIORITY_NORMAL
#define PRIORITY_HIGH_VALUE   THREAD_PRIORITY_ABOVE_NORMAL
#define PRIORITY_URGENT_VALUE THREAD_PRIORITY_HIGHEST

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 GTryEnterCriticalSectionFunc try_enter_critical_section = NULL;

/* As noted in the docs, GPrivate is a limited resource, here we take
 * a rather low maximum to save memory, use GStaticPrivate instead. */
73
#define G_PRIVATE_MAX 100
74 75 76 77 78

static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];

static guint g_private_next = 0;

79 80 81
/* A "forward" declaration of this structure */
static GThreadFunctions g_thread_functions_for_glib_use_default;

82 83 84 85 86 87 88 89 90
typedef struct _GThreadData GThreadData;
struct _GThreadData
{
  GThreadFunc func;
  gpointer data;
  HANDLE thread;
  gboolean joinable;
};

91
struct _GCond
92 93 94 95 96 97 98 99
{
  GPtrArray *array;
  CRITICAL_SECTION lock;
};

static GMutex *
g_mutex_new_win32_cs_impl (void)
{
100 101 102 103 104
  CRITICAL_SECTION *cs = g_new (CRITICAL_SECTION, 1);
  gpointer *retval = g_new (gpointer, 1);

  InitializeCriticalSection (cs);
  *retval = cs;
105 106 107 108 109 110
  return (GMutex *) retval;
}

static void
g_mutex_free_win32_cs_impl (GMutex *mutex)
{
111 112 113 114 115
  gpointer *ptr = (gpointer *) mutex;
  CRITICAL_SECTION *cs = (CRITICAL_SECTION *) *ptr;

  DeleteCriticalSection (cs);
  g_free (cs);
116 117 118 119 120 121 122 123 124
  g_free (mutex);
}

/* 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_cs_impl (GMutex *mutex)
{
125
  EnterCriticalSection (*(CRITICAL_SECTION **)mutex);
126 127 128 129 130
}

static gboolean
g_mutex_trylock_win32_cs_impl (GMutex * mutex)
{
131
  return try_enter_critical_section (*(CRITICAL_SECTION **)mutex);
132 133 134 135 136
}

static void
g_mutex_unlock_win32_cs_impl (GMutex *mutex)
{
137
  LeaveCriticalSection (*(CRITICAL_SECTION **)mutex);
138 139 140 141 142 143
}

static GMutex *
g_mutex_new_win32_impl (void)
{
  HANDLE handle;
144
  HANDLE *retval;
145
  win32_check_for_error (handle = CreateMutex (NULL, FALSE, NULL));
146 147 148
  retval = g_new (HANDLE, 1);
  *retval = handle;
  return (GMutex *) retval;
149 150 151 152 153
}

static void
g_mutex_free_win32_impl (GMutex *mutex)
{
154 155
  win32_check_for_error (CloseHandle (*(HANDLE *) mutex));
  g_free (mutex);
156 157 158 159 160 161 162 163
}

/* 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)
{
164
  WaitForSingleObject (*(HANDLE *) mutex, INFINITE);
165 166 167 168 169 170
}

static gboolean
g_mutex_trylock_win32_impl (GMutex * mutex)
{
  DWORD result;
171
  win32_check_for_error (WAIT_FAILED !=
172
			 (result = WaitForSingleObject (*(HANDLE *)mutex, 0)));
173 174 175 176 177 178
  return result != WAIT_TIMEOUT;
}

static void
g_mutex_unlock_win32_impl (GMutex *mutex)
{
179
  ReleaseMutex (*(HANDLE *) mutex);
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
}

static GCond *
g_cond_new_win32_impl (void)
{
  GCond *retval = g_new (GCond, 1);

  retval->array = g_ptr_array_new ();
  InitializeCriticalSection (&retval->lock);

  return retval;
}

static void
g_cond_signal_win32_impl (GCond * cond)
{
  EnterCriticalSection (&cond->lock);

  if (cond->array->len > 0)
    {
      SetEvent (g_ptr_array_index (cond->array, 0));
      g_ptr_array_remove_index (cond->array, 0);
    }

  LeaveCriticalSection (&cond->lock);
}

static void
g_cond_broadcast_win32_impl (GCond * cond)
{
  guint i;
  EnterCriticalSection (&cond->lock);

  for (i = 0; i < cond->array->len; i++)
    SetEvent (g_ptr_array_index (cond->array, i));

  g_ptr_array_set_size (cond->array, 0);
  LeaveCriticalSection (&cond->lock);
}

static gboolean
g_cond_wait_internal (GCond *cond,
		      GMutex *entered_mutex,
		      gulong milliseconds)
{
  gulong retval;
  HANDLE event = TlsGetValue (g_cond_event_tls);

  if (!event)
    {
      win32_check_for_error (event = CreateEvent (0, FALSE, FALSE, NULL));
      TlsSetValue (g_cond_event_tls, event);
    }

  EnterCriticalSection (&cond->lock);

  /* The event must not be signaled. Check this */
  g_assert (WaitForSingleObject (event, 0) == WAIT_TIMEOUT);

  g_ptr_array_add (cond->array, event);
  LeaveCriticalSection (&cond->lock);

242
  g_thread_functions_for_glib_use_default.mutex_unlock (entered_mutex);
243 244 245 246

  win32_check_for_error (WAIT_FAILED !=
			 (retval = WaitForSingleObject (event, milliseconds)));

247
  g_thread_functions_for_glib_use_default.mutex_lock (entered_mutex);
248 249 250 251 252 253 254

  if (retval == WAIT_TIMEOUT)
    {
      EnterCriticalSection (&cond->lock);
      g_ptr_array_remove (cond->array, event);

      /* In the meantime we could have been signaled, so we must again
255 256 257
       * wait for the signal, this time with no timeout, to reset
       * it. retval is set again to honour the late arrival of the
       * signal */
258
      win32_check_for_error (WAIT_FAILED !=
259
			     (retval = WaitForSingleObject (event, 0)));
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

      LeaveCriticalSection (&cond->lock);
    }

#ifndef G_DISABLE_ASSERT
  EnterCriticalSection (&cond->lock);

  /* Now event must not be inside the array, check this */
  g_assert (g_ptr_array_remove (cond->array, event) == FALSE);

  LeaveCriticalSection (&cond->lock);
#endif /* !G_DISABLE_ASSERT */

  return retval != WAIT_TIMEOUT;
}

276
static void
277 278 279 280 281 282 283 284 285 286
g_cond_wait_win32_impl (GCond *cond,
			GMutex *entered_mutex)
{
  g_return_if_fail (cond != NULL);
  g_return_if_fail (entered_mutex != NULL);

  g_cond_wait_internal (cond, entered_mutex, INFINITE);
}

static gboolean
287
g_cond_timed_wait_win32_impl (GCond *cond,
288 289 290 291 292 293 294 295 296
			      GMutex *entered_mutex,
			      GTimeVal *abs_time)
{
  GTimeVal current_time;
  gulong to_wait;

  g_return_val_if_fail (cond != NULL, FALSE);
  g_return_val_if_fail (entered_mutex != NULL, FALSE);

297 298 299 300 301 302 303 304 305 306 307
  if (!abs_time)
    to_wait = INFINITE;
  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 +
308
	  (abs_time->tv_usec - current_time.tv_usec) / 1000;
309
    }
310

311 312 313 314 315 316
  return g_cond_wait_internal (cond, entered_mutex, to_wait);
}

static void
g_cond_free_win32_impl (GCond * cond)
{
317
  DeleteCriticalSection (&cond->lock);
318 319 320 321 322 323 324 325 326 327
  g_ptr_array_free (cond->array, TRUE);
  g_free (cond);
}

static GPrivate *
g_private_new_win32_impl (GDestroyNotify destructor)
{
  GPrivate *result;
  EnterCriticalSection (&g_thread_global_spinlock);
  if (g_private_next >= G_PRIVATE_MAX)
328 329 330 331 332 333 334 335 336 337
    {
      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 ();
    }
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  g_private_destructors[g_private_next] = destructor;
  result = GUINT_TO_POINTER (g_private_next);
  g_private_next++;
  LeaveCriticalSection (&g_thread_global_spinlock);

  return result;
}

/* 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)
{
  gpointer* array = TlsGetValue (g_private_tls);
  guint index = GPOINTER_TO_UINT (private_key);

  if (index >= G_PRIVATE_MAX)
      return;

  if (!array)
    {
      array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
      TlsSetValue (g_private_tls, array);
    }

  array[index] = value;
}

static gpointer
g_private_get_win32_impl (GPrivate * private_key)
{
  gpointer* array = TlsGetValue (g_private_tls);
  guint index = GPOINTER_TO_UINT (private_key);

  if (index >= G_PRIVATE_MAX || !array)
    return NULL;

  return array[index];
}

static void
g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
{
  GThreadData *target = *(GThreadData **)thread;

  g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
  g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);

387
  win32_check_for_error (SetThreadPriority (target->thread,
388 389 390 391 392
					    g_thread_priority_map [priority]));
}

static void
g_thread_self_win32_impl (gpointer thread)
393
{
394 395 396 397 398 399 400 401
  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);
402 403
      win32_check_for_error (DuplicateHandle (process, handle, process,
					      &self->thread, 0, FALSE,
404 405 406
					      DUPLICATE_SAME_ACCESS));
      win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
      self->func = NULL;
407
      self->data = NULL;
408 409 410 411 412 413
      self->joinable = FALSE;
    }

  *(GThreadData **)thread = self;
}

414
static void
415 416 417 418 419 420 421 422 423 424 425 426 427
g_thread_exit_win32_impl (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);

  EnterCriticalSection (&g_thread_global_spinlock);
  private_max = g_private_next;
  LeaveCriticalSection (&g_thread_global_spinlock);

  if (array)
    {
428 429 430 431 432 433 434 435
      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];
436

437 438 439 440
	    if (data)
	      some_data_non_null = TRUE;

	    array[i] = NULL;
441

442 443 444 445
	    if (destructor && data)
	      destructor (data);
	  }
      } while (some_data_non_null);
446

447
      free (array);
448 449 450

      win32_check_for_error (TlsSetValue (g_private_tls, NULL));
    }
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  if (self)
    {
      if (!self->joinable)
	{
	  win32_check_for_error (CloseHandle (self->thread));
	  g_free (self);
	}
      win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
    }

  if (event)
    {
      CloseHandle (event);
      win32_check_for_error (TlsSetValue (g_cond_event_tls, NULL));
    }

  _endthreadex (0);
}

static guint __stdcall
g_thread_proxy (gpointer data)
{
  GThreadData *self = (GThreadData*) data;

  win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
477

478 479 480 481 482 483 484 485 486 487
  self->func (self->data);

  g_thread_exit_win32_impl ();

  g_assert_not_reached ();

  return 0;
}

static void
488 489
g_thread_create_win32_impl (GThreadFunc func,
			    gpointer data,
490 491 492 493 494 495
			    gulong stack_size,
			    gboolean joinable,
			    gboolean bound,
			    GThreadPriority priority,
			    gpointer thread,
			    GError **error)
496
{
497 498 499 500 501 502
  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);
503

504 505 506
  retval = g_new(GThreadData, 1);
  retval->func = func;
  retval->data = data;
507

508 509
  retval->joinable = joinable;

510
  retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
511 512 513 514
					    retval, 0, &ignore);

  if (retval->thread == NULL)
    {
515
      gchar *win_error = g_win32_error_message (GetLastError ());
516
      g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
517 518 519
                   "Error creating thread: %s", win_error);
      g_free (retval);
      g_free (win_error);
520 521 522 523 524 525 526 527
      return;
    }

  *(GThreadData **)thread = retval;

  g_thread_set_priority_win32_impl (thread, priority);
}

528
static void
529 530 531 532 533 534 535 536 537 538 539 540
g_thread_yield_win32_impl (void)
{
  Sleep(0);
}

static void
g_thread_join_win32_impl (gpointer thread)
{
  GThreadData *target = *(GThreadData **)thread;

  g_return_if_fail (target->joinable);

541
  win32_check_for_error (WAIT_FAILED !=
542 543 544 545 546 547
			 WaitForSingleObject (target->thread, INFINITE));

  win32_check_for_error (CloseHandle (target->thread));
  g_free (target);
}

548 549 550 551 552 553 554 555 556 557
static guint64
g_gettime_win32_impl (void)
{
  guint64 v;

  GetSystemTimeAsFileTime ((FILETIME *)&v);

  return v;
}

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
static GThreadFunctions g_thread_functions_for_glib_use_default =
{
  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,
579
  g_thread_self_win32_impl,
580 581
  NULL,                             /* no equal function necessary */
  g_gettime_win32_impl
582 583 584 585 586 587
};

#define HAVE_G_THREAD_IMPL_INIT
static void
g_thread_impl_init ()
{
588
  static gboolean beenhere = FALSE;
589 590
  HMODULE kernel32;

591 592 593 594
  if (beenhere)
    return;

  beenhere = TRUE;
595 596

  win32_check_for_error (TLS_OUT_OF_INDEXES !=
597
			 (g_thread_self_tls = TlsAlloc ()));
598
  win32_check_for_error (TLS_OUT_OF_INDEXES !=
599
			 (g_private_tls = TlsAlloc ()));
600
  win32_check_for_error (TLS_OUT_OF_INDEXES !=
601 602 603 604
			 (g_cond_event_tls = TlsAlloc ()));
  InitializeCriticalSection (&g_thread_global_spinlock);

  /* Here we are looking for TryEnterCriticalSection in KERNEL32.DLL,
605 606 607 608
   * if it is found, we can use the in general faster critical
   * sections instead of mutexes. See
   * http://world.std.com/~jmhart/csmutx.htm for some discussion.
   */
609 610 611 612 613
  kernel32 = GetModuleHandle ("KERNEL32.DLL");
  if (kernel32)
    {
      try_enter_critical_section = (GTryEnterCriticalSectionFunc)
	GetProcAddress(kernel32, "TryEnterCriticalSection");
614

615 616
      /* Even if TryEnterCriticalSection is found, it is not
       * necessarily working..., we have to check it */
617
      if (try_enter_critical_section &&
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
	  try_enter_critical_section (&g_thread_global_spinlock))
	{
	  LeaveCriticalSection (&g_thread_global_spinlock);

	  g_thread_functions_for_glib_use_default.mutex_new =
	    g_mutex_new_win32_cs_impl;
	  g_thread_functions_for_glib_use_default.mutex_lock =
	    g_mutex_lock_win32_cs_impl;
	  g_thread_functions_for_glib_use_default.mutex_trylock =
	    g_mutex_trylock_win32_cs_impl;
	  g_thread_functions_for_glib_use_default.mutex_unlock =
	    g_mutex_unlock_win32_cs_impl;
	  g_thread_functions_for_glib_use_default.mutex_free =
	    g_mutex_free_win32_cs_impl;
	}
    }
}