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