invert gthread-impl includes
[platform/upstream/glib.git] / gthread / 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 /*
32  * MT safe
33  */
34
35 #include "config.h"
36
37 #include "glib.h"
38 #include "gthreadprivate.h"
39
40 #define STRICT
41 #define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
42 #include <windows.h>
43 #undef STRICT
44
45 #include <process.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48
49 #define win32_check_for_error(what) G_STMT_START{                       \
50   if (!(what))                                                          \
51     g_error ("file %s: line %d (%s): error %s during %s",               \
52              __FILE__, __LINE__, G_STRFUNC,                             \
53              g_win32_error_message (GetLastError ()), #what);           \
54   }G_STMT_END
55
56 #define G_MUTEX_SIZE (sizeof (gpointer))
57
58 static DWORD g_thread_self_tls;
59 static DWORD g_private_tls;
60 static DWORD g_cond_event_tls;
61 static CRITICAL_SECTION g_thread_global_spinlock;
62
63 typedef BOOL (__stdcall *GTryEnterCriticalSectionFunc) (CRITICAL_SECTION *);
64
65 /* As noted in the docs, GPrivate is a limited resource, here we take
66  * a rather low maximum to save memory, use GStaticPrivate instead. */
67 #define G_PRIVATE_MAX 100
68
69 static GDestroyNotify g_private_destructors[G_PRIVATE_MAX];
70
71 static guint g_private_next = 0;
72
73 /* A "forward" declaration of this structure */
74 static GThreadFunctions g_thread_functions_for_glib_use_default;
75
76 typedef struct _GThreadData GThreadData;
77 struct _GThreadData
78 {
79   GThreadFunc func;
80   gpointer data;
81   HANDLE thread;
82   gboolean joinable;
83 };
84
85 struct _GCond
86 {
87   GPtrArray *array;
88   CRITICAL_SECTION lock;
89 };
90
91 static GMutex *
92 g_mutex_new_win32_impl (void)
93 {
94   CRITICAL_SECTION *cs = g_new (CRITICAL_SECTION, 1);
95   gpointer *retval = g_new (gpointer, 1);
96
97   InitializeCriticalSection (cs);
98   *retval = cs;
99   return (GMutex *) retval;
100 }
101
102 static void
103 g_mutex_free_win32_impl (GMutex *mutex)
104 {
105   gpointer *ptr = (gpointer *) mutex;
106   CRITICAL_SECTION *cs = (CRITICAL_SECTION *) *ptr;
107
108   DeleteCriticalSection (cs);
109   g_free (cs);
110   g_free (mutex);
111 }
112
113 /* NOTE: the functions g_mutex_lock and g_mutex_unlock may not use
114    functions from gmem.c and gmessages.c; */
115
116 static void
117 g_mutex_lock_win32_impl (GMutex *mutex)
118 {
119   EnterCriticalSection (*(CRITICAL_SECTION **)mutex);
120 }
121
122 static gboolean
123 g_mutex_trylock_win32_impl (GMutex * mutex)
124 {
125   return TryEnterCriticalSection (*(CRITICAL_SECTION **)mutex);
126 }
127
128 static void
129 g_mutex_unlock_win32_impl (GMutex *mutex)
130 {
131   LeaveCriticalSection (*(CRITICAL_SECTION **)mutex);
132 }
133
134 static GCond *
135 g_cond_new_win32_impl (void)
136 {
137   GCond *retval = g_new (GCond, 1);
138
139   retval->array = g_ptr_array_new ();
140   InitializeCriticalSection (&retval->lock);
141
142   return retval;
143 }
144
145 static void
146 g_cond_signal_win32_impl (GCond * cond)
147 {
148   EnterCriticalSection (&cond->lock);
149
150   if (cond->array->len > 0)
151     {
152       SetEvent (g_ptr_array_index (cond->array, 0));
153       g_ptr_array_remove_index (cond->array, 0);
154     }
155
156   LeaveCriticalSection (&cond->lock);
157 }
158
159 static void
160 g_cond_broadcast_win32_impl (GCond * cond)
161 {
162   guint i;
163   EnterCriticalSection (&cond->lock);
164
165   for (i = 0; i < cond->array->len; i++)
166     SetEvent (g_ptr_array_index (cond->array, i));
167
168   g_ptr_array_set_size (cond->array, 0);
169   LeaveCriticalSection (&cond->lock);
170 }
171
172 static gboolean
173 g_cond_wait_internal (GCond *cond,
174                       GMutex *entered_mutex,
175                       gulong milliseconds)
176 {
177   gulong retval;
178   HANDLE event = TlsGetValue (g_cond_event_tls);
179
180   if (!event)
181     {
182       win32_check_for_error (event = CreateEvent (0, FALSE, FALSE, NULL));
183       TlsSetValue (g_cond_event_tls, event);
184     }
185
186   EnterCriticalSection (&cond->lock);
187
188   /* The event must not be signaled. Check this */
189   g_assert (WaitForSingleObject (event, 0) == WAIT_TIMEOUT);
190
191   g_ptr_array_add (cond->array, event);
192   LeaveCriticalSection (&cond->lock);
193
194   g_mutex_unlock (entered_mutex);
195
196   win32_check_for_error (WAIT_FAILED !=
197                          (retval = WaitForSingleObject (event, milliseconds)));
198
199   g_mutex_lock (entered_mutex);
200
201   if (retval == WAIT_TIMEOUT)
202     {
203       EnterCriticalSection (&cond->lock);
204       g_ptr_array_remove (cond->array, event);
205
206       /* In the meantime we could have been signaled, so we must again
207        * wait for the signal, this time with no timeout, to reset
208        * it. retval is set again to honour the late arrival of the
209        * signal */
210       win32_check_for_error (WAIT_FAILED !=
211                              (retval = WaitForSingleObject (event, 0)));
212
213       LeaveCriticalSection (&cond->lock);
214     }
215
216 #ifndef G_DISABLE_ASSERT
217   EnterCriticalSection (&cond->lock);
218
219   /* Now event must not be inside the array, check this */
220   g_assert (g_ptr_array_remove (cond->array, event) == FALSE);
221
222   LeaveCriticalSection (&cond->lock);
223 #endif /* !G_DISABLE_ASSERT */
224
225   return retval != WAIT_TIMEOUT;
226 }
227
228 static void
229 g_cond_wait_win32_impl (GCond *cond,
230                         GMutex *entered_mutex)
231 {
232   g_return_if_fail (cond != NULL);
233   g_return_if_fail (entered_mutex != NULL);
234
235   g_cond_wait_internal (cond, entered_mutex, INFINITE);
236 }
237
238 static gboolean
239 g_cond_timed_wait_win32_impl (GCond *cond,
240                               GMutex *entered_mutex,
241                               GTimeVal *abs_time)
242 {
243   GTimeVal current_time;
244   gulong to_wait;
245
246   g_return_val_if_fail (cond != NULL, FALSE);
247   g_return_val_if_fail (entered_mutex != NULL, FALSE);
248
249   if (!abs_time)
250     to_wait = INFINITE;
251   else
252     {
253       g_get_current_time (&current_time);
254       if (abs_time->tv_sec < current_time.tv_sec ||
255           (abs_time->tv_sec == current_time.tv_sec &&
256            abs_time->tv_usec <= current_time.tv_usec))
257         to_wait = 0;
258       else
259         to_wait = (abs_time->tv_sec - current_time.tv_sec) * 1000 +
260           (abs_time->tv_usec - current_time.tv_usec) / 1000;
261     }
262
263   return g_cond_wait_internal (cond, entered_mutex, to_wait);
264 }
265
266 static void
267 g_cond_free_win32_impl (GCond * cond)
268 {
269   DeleteCriticalSection (&cond->lock);
270   g_ptr_array_free (cond->array, TRUE);
271   g_free (cond);
272 }
273
274 static GPrivate *
275 g_private_new_win32_impl (GDestroyNotify destructor)
276 {
277   GPrivate *result;
278   EnterCriticalSection (&g_thread_global_spinlock);
279   if (g_private_next >= G_PRIVATE_MAX)
280     {
281       char buf[100];
282       sprintf (buf,
283                "Too many GPrivate allocated. Their number is limited to %d.",
284                G_PRIVATE_MAX);
285       MessageBox (NULL, buf, NULL, MB_ICONERROR|MB_SETFOREGROUND);
286       if (IsDebuggerPresent ())
287         G_BREAKPOINT ();
288       abort ();
289     }
290   g_private_destructors[g_private_next] = destructor;
291   result = GUINT_TO_POINTER (g_private_next);
292   g_private_next++;
293   LeaveCriticalSection (&g_thread_global_spinlock);
294
295   return result;
296 }
297
298 /* NOTE: the functions g_private_get and g_private_set may not use
299    functions from gmem.c and gmessages.c */
300
301 static void
302 g_private_set_win32_impl (GPrivate * private_key, gpointer value)
303 {
304   gpointer* array = TlsGetValue (g_private_tls);
305   guint index = GPOINTER_TO_UINT (private_key);
306
307   if (index >= G_PRIVATE_MAX)
308       return;
309
310   if (!array)
311     {
312       array = (gpointer*) calloc (G_PRIVATE_MAX, sizeof (gpointer));
313       TlsSetValue (g_private_tls, array);
314     }
315
316   array[index] = value;
317 }
318
319 static gpointer
320 g_private_get_win32_impl (GPrivate * private_key)
321 {
322   gpointer* array = TlsGetValue (g_private_tls);
323   guint index = GPOINTER_TO_UINT (private_key);
324
325   if (index >= G_PRIVATE_MAX || !array)
326     return NULL;
327
328   return array[index];
329 }
330
331 static void
332 g_thread_set_priority_win32_impl (gpointer thread, GThreadPriority priority)
333 {
334   GThreadData *target = *(GThreadData **)thread;
335   gint native_prio;
336
337   switch (priority)
338     {
339     case G_THREAD_PRIORITY_LOW:
340       native_prio = THREAD_PRIORITY_BELOW_NORMAL;
341       break;
342
343     case G_THREAD_PRIORITY_NORMAL:
344       native_prio = THREAD_PRIORITY_NORMAL;
345       break;
346
347     case G_THREAD_PRIORITY_HIGH:
348       native_prio = THREAD_PRIORITY_ABOVE_NORMAL;
349       break;
350
351     case G_THREAD_PRIORITY_URGENT:
352       native_prio = THREAD_PRIORITY_HIGHEST;
353       break;
354
355     default:
356       g_return_if_reached ();
357     }
358
359   win32_check_for_error (SetThreadPriority (target->thread, native_prio));
360 }
361
362 static void
363 g_thread_self_win32_impl (gpointer thread)
364 {
365   GThreadData *self = TlsGetValue (g_thread_self_tls);
366
367   if (!self)
368     {
369       /* This should only happen for the main thread! */
370       HANDLE handle = GetCurrentThread ();
371       HANDLE process = GetCurrentProcess ();
372       self = g_new (GThreadData, 1);
373       win32_check_for_error (DuplicateHandle (process, handle, process,
374                                               &self->thread, 0, FALSE,
375                                               DUPLICATE_SAME_ACCESS));
376       win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
377       self->func = NULL;
378       self->data = NULL;
379       self->joinable = FALSE;
380     }
381
382   *(GThreadData **)thread = self;
383 }
384
385 static void
386 g_thread_exit_win32_impl (void)
387 {
388   GThreadData *self = TlsGetValue (g_thread_self_tls);
389   guint i, private_max;
390   gpointer *array = TlsGetValue (g_private_tls);
391   HANDLE event = TlsGetValue (g_cond_event_tls);
392
393   EnterCriticalSection (&g_thread_global_spinlock);
394   private_max = g_private_next;
395   LeaveCriticalSection (&g_thread_global_spinlock);
396
397   if (array)
398     {
399       gboolean some_data_non_null;
400
401       do {
402         some_data_non_null = FALSE;
403         for (i = 0; i < private_max; i++)
404           {
405             GDestroyNotify destructor = g_private_destructors[i];
406             GDestroyNotify data = array[i];
407
408             if (data)
409               some_data_non_null = TRUE;
410
411             array[i] = NULL;
412
413             if (destructor && data)
414               destructor (data);
415           }
416       } while (some_data_non_null);
417
418       free (array);
419
420       win32_check_for_error (TlsSetValue (g_private_tls, NULL));
421     }
422
423   if (self)
424     {
425       if (!self->joinable)
426         {
427           win32_check_for_error (CloseHandle (self->thread));
428           g_free (self);
429         }
430       win32_check_for_error (TlsSetValue (g_thread_self_tls, NULL));
431     }
432
433   if (event)
434     {
435       CloseHandle (event);
436       win32_check_for_error (TlsSetValue (g_cond_event_tls, NULL));
437     }
438
439   _endthreadex (0);
440 }
441
442 static guint __stdcall
443 g_thread_proxy (gpointer data)
444 {
445   GThreadData *self = (GThreadData*) data;
446
447   win32_check_for_error (TlsSetValue (g_thread_self_tls, self));
448
449   self->func (self->data);
450
451   g_thread_exit_win32_impl ();
452
453   g_assert_not_reached ();
454
455   return 0;
456 }
457
458 static void
459 g_thread_create_win32_impl (GThreadFunc func,
460                             gpointer data,
461                             gulong stack_size,
462                             gboolean joinable,
463                             gboolean bound,
464                             GThreadPriority priority,
465                             gpointer thread,
466                             GError **error)
467 {
468   guint ignore;
469   GThreadData *retval;
470
471   g_return_if_fail (func);
472   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
473   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
474
475   retval = g_new(GThreadData, 1);
476   retval->func = func;
477   retval->data = data;
478
479   retval->joinable = joinable;
480
481   retval->thread = (HANDLE) _beginthreadex (NULL, stack_size, g_thread_proxy,
482                                             retval, 0, &ignore);
483
484   if (retval->thread == NULL)
485     {
486       gchar *win_error = g_win32_error_message (GetLastError ());
487       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
488                    "Error creating thread: %s", win_error);
489       g_free (retval);
490       g_free (win_error);
491       return;
492     }
493
494   *(GThreadData **)thread = retval;
495
496   g_thread_set_priority_win32_impl (thread, priority);
497 }
498
499 static void
500 g_thread_yield_win32_impl (void)
501 {
502   Sleep(0);
503 }
504
505 static void
506 g_thread_join_win32_impl (gpointer thread)
507 {
508   GThreadData *target = *(GThreadData **)thread;
509
510   g_return_if_fail (target->joinable);
511
512   win32_check_for_error (WAIT_FAILED !=
513                          WaitForSingleObject (target->thread, INFINITE));
514
515   win32_check_for_error (CloseHandle (target->thread));
516   g_free (target);
517 }
518
519 static GThreadFunctions g_thread_functions_for_glib_use_default =
520 {
521   g_mutex_new_win32_impl,           /* mutex */
522   g_mutex_lock_win32_impl,
523   g_mutex_trylock_win32_impl,
524   g_mutex_unlock_win32_impl,
525   g_mutex_free_win32_impl,
526   g_cond_new_win32_impl,            /* condition */
527   g_cond_signal_win32_impl,
528   g_cond_broadcast_win32_impl,
529   g_cond_wait_win32_impl,
530   g_cond_timed_wait_win32_impl,
531   g_cond_free_win32_impl,
532   g_private_new_win32_impl,         /* private thread data */
533   g_private_get_win32_impl,
534   g_private_set_win32_impl,
535   g_thread_create_win32_impl,       /* thread */
536   g_thread_yield_win32_impl,
537   g_thread_join_win32_impl,
538   g_thread_exit_win32_impl,
539   g_thread_set_priority_win32_impl,
540   g_thread_self_win32_impl,
541   NULL                             /* no equal function necessary */
542 };
543
544 static void
545 g_thread_impl_init ()
546 {
547   static gboolean beenhere = FALSE;
548
549   if (beenhere)
550     return;
551
552   beenhere = TRUE;
553
554   win32_check_for_error (TLS_OUT_OF_INDEXES !=
555                          (g_thread_self_tls = TlsAlloc ()));
556   win32_check_for_error (TLS_OUT_OF_INDEXES !=
557                          (g_private_tls = TlsAlloc ()));
558   win32_check_for_error (TLS_OUT_OF_INDEXES !=
559                          (g_cond_event_tls = TlsAlloc ()));
560   InitializeCriticalSection (&g_thread_global_spinlock);
561 }
562
563 #include "gthread-impl.c"