check for sysconf (_SC_THREAD_STACK_MIN), which returns the minimal stack
[platform/upstream/glib.git] / gthread.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmutex.c: MT safety related functions
5  * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6  *                Owen Taylor
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library 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  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library 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-1999.  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 #include "glib.h"
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 typedef union _SystemThread SystemThread;
43
44 /* This represents a system thread as used by the implementation. An
45  * alien implementaion, as loaded by g_thread_init can only count on
46  * "sizeof (gpointer)" bytes to store their info. We however need more
47  * for some of our native implementations. */
48 union _SystemThread
49 {
50   guchar   data[GLIB_SIZEOF_SYSTEM_THREAD];
51   gdouble  double_dummy; /* These are used for the right alignment */
52   gpointer pointer_dummy;
53 #ifdef G_HAVE_GINT64
54   guint64  long_dummy;
55 #else
56   guint32  long_dummy;  
57 #endif
58 };
59
60 typedef struct _GRealThread GRealThread;
61
62 struct  _GRealThread
63 {
64   GThread thread;
65   GThreadFunc func;
66   gpointer arg;
67   gpointer private_data;
68   SystemThread system_thread;
69 };
70
71 #if (GLIB_SIZEOF_SYSTEM_THREAD <= 8 && defined(G_HAVE_GINT64))               \
72   || (GLIB_SIZEOF_SYSTEM_THREAD <= 4)
73 /* We can use fast setting and checks */
74 #  define set_system_thread_to_zero(t) (t->system_thread.long_dummy=0)
75 #  define system_thread_is_not_zero(t) (t->system_thread.long_dummy)
76 #else
77 /* We have to do it the hard way and hope the compiler will optimize a bit */
78 static inline void
79 set_system_thread_to_zero(GRealThread* thread)
80
81   int i; 
82   for (i = 0; i < GLIB_SIZEOF_SYSTEM_THREAD; i++)
83     thread->system_thread.data[i] = 0;
84 }
85
86 static inline gboolean
87 system_thread_is_not_zero(GRealThread* thread)
88 {
89   int i; 
90   for (i = 0; i < GLIB_SIZEOF_SYSTEM_THREAD; i++)
91     if (thread->system_thread.data[i]) return FALSE;
92   return TRUE;
93 }
94 #endif
95
96 typedef struct _GStaticPrivateNode GStaticPrivateNode;
97
98 struct _GStaticPrivateNode
99 {
100   gpointer       data;
101   GDestroyNotify destroy;
102 };
103
104 static void g_thread_cleanup (gpointer data);
105 static void g_thread_fail (void);
106
107 /* Global variables */
108
109 gboolean g_thread_use_default_impl = TRUE;
110 gboolean g_threads_got_initialized = FALSE;
111
112 #if defined(G_OS_WIN32) && defined(__GNUC__)
113 __declspec(dllexport)
114 #endif
115 GThreadFunctions g_thread_functions_for_glib_use = {
116   (GMutex*(*)())g_thread_fail,                 /* mutex_new */
117   NULL,                                        /* mutex_lock */
118   NULL,                                        /* mutex_trylock */
119   NULL,                                        /* mutex_unlock */
120   NULL,                                        /* mutex_free */
121   (GCond*(*)())g_thread_fail,                  /* cond_new */
122   NULL,                                        /* cond_signal */
123   NULL,                                        /* cond_broadcast */
124   NULL,                                        /* cond_wait */
125   NULL,                                        /* cond_timed_wait  */
126   NULL,                                        /* cond_free */
127   (GPrivate*(*)(GDestroyNotify))g_thread_fail, /* private_new */
128   NULL,                                        /* private_get */
129   NULL,                                        /* private_set */
130   (void(*)(GThreadFunc, gpointer, gulong, 
131            gboolean, gboolean, GThreadPriority, 
132            gpointer))g_thread_fail,            /* thread_create */
133   NULL,                                        /* thread_yield */
134   NULL,                                        /* thread_join */
135   NULL,                                        /* thread_exit */
136   NULL,                                        /* thread_set_priority */
137   NULL                                         /* thread_self */
138 }; 
139
140 /* Local data */
141
142 static GMutex   *g_mutex_protect_static_mutex_allocation = NULL;
143 static GMutex   *g_thread_specific_mutex = NULL;
144 static GPrivate *g_thread_specific_private = NULL;
145
146 /* This must be called only once, before any threads are created.
147  * It will only be called from g_thread_init() in -lgthread.
148  */
149 void
150 g_mutex_init (void)
151 {
152   gpointer private_old;
153  
154   /* We let the main thread (the one that calls g_thread_init) inherit
155    * the data, that it set before calling g_thread_init
156    */
157   private_old = g_thread_specific_private;
158
159   g_thread_specific_private = g_private_new (g_thread_cleanup);
160
161   /* we can not use g_private_set here, as g_threads_got_initialized is not
162    * yet set TRUE, whereas the private_set function is already set.
163    */
164   g_thread_functions_for_glib_use.private_set (g_thread_specific_private, 
165                                                private_old);
166
167   g_mutex_protect_static_mutex_allocation = g_mutex_new();
168   g_thread_specific_mutex = g_mutex_new();
169   
170 }
171
172 GMutex *
173 g_static_mutex_get_mutex_impl (GMutex** mutex)
174 {
175   if (!g_thread_supported ())
176     return NULL;
177
178   g_assert (g_mutex_protect_static_mutex_allocation);
179
180   g_mutex_lock (g_mutex_protect_static_mutex_allocation);
181
182   if (!(*mutex)) 
183     *mutex = g_mutex_new(); 
184
185   g_mutex_unlock (g_mutex_protect_static_mutex_allocation);
186   
187   return *mutex;
188 }
189
190 #ifndef g_static_rec_mutex_lock
191 /* That means, that g_static_rec_mutex_lock is not defined to be 
192  * g_static_mutex_lock, we have to provide an implementation ourselves.
193  */
194 void
195 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
196 {
197   guint counter = GPOINTER_TO_UINT (g_static_private_get (&mutex->counter));
198   if (counter == 0)
199     {
200       g_static_mutex_lock (&mutex->mutex);
201     }
202   counter++;
203   g_static_private_set (&mutex->counter, GUINT_TO_POINTER (counter), NULL);
204 }
205
206 gboolean
207 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
208 {
209   guint counter = GPOINTER_TO_UINT (g_static_private_get (&mutex->counter));
210   if (counter == 0)
211     {
212       if (!g_static_mutex_trylock (&mutex->mutex)) return FALSE;
213     }
214   counter++;
215   g_static_private_set (&mutex->counter, GUINT_TO_POINTER (counter), NULL);
216   return TRUE;
217 }
218
219 void
220 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
221 {
222   guint counter = GPOINTER_TO_UINT (g_static_private_get (&mutex->counter));
223   if (counter == 1)
224     {
225       g_static_mutex_unlock (&mutex->mutex);
226     }
227   counter--;
228   g_static_private_set (&mutex->counter, GUINT_TO_POINTER (counter), NULL);
229 }
230 #endif /* g_static_rec_mutex_lock */
231
232 gpointer
233 g_static_private_get (GStaticPrivate *private_key)
234 {
235   return g_static_private_get_for_thread (private_key, g_thread_self ());
236 }
237
238 gpointer
239 g_static_private_get_for_thread (GStaticPrivate *private_key,
240                                  GThread        *thread)
241 {
242   GArray *array;
243   GRealThread *self = (GRealThread*) thread;
244
245   g_return_val_if_fail (thread, NULL);
246
247   array = self->private_data;
248   if (!array)
249     return NULL;
250
251   if (!private_key->index)
252     return NULL;
253   else if (private_key->index <= array->len)
254     return g_array_index (array, GStaticPrivateNode, private_key->index - 1).data;
255   else
256     return NULL;
257 }
258
259 void
260 g_static_private_set (GStaticPrivate *private_key, 
261                       gpointer        data,
262                       GDestroyNotify  notify)
263 {
264   g_static_private_set_for_thread (private_key, g_thread_self (), 
265                                    data, notify);
266 }
267
268 void
269 g_static_private_set_for_thread (GStaticPrivate *private_key, 
270                                  GThread        *thread,
271                                  gpointer        data,
272                                  GDestroyNotify  notify)
273 {
274   GArray *array;
275   GRealThread *self =(GRealThread*) thread;
276   static guint next_index = 0;
277   GStaticPrivateNode *node;
278
279   g_return_if_fail (thread);
280   
281   array = self->private_data;
282   if (!array)
283     {
284       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
285       self->private_data = array;
286     }
287
288   if (!private_key->index)
289     {
290       g_mutex_lock (g_thread_specific_mutex);
291
292       if (!private_key->index)
293         private_key->index = ++next_index;
294
295       g_mutex_unlock (g_thread_specific_mutex);
296     }
297
298   if (private_key->index > array->len)
299     g_array_set_size (array, private_key->index);
300
301   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
302   if (node->destroy)
303     {
304       gpointer ddata = node->data;
305       GDestroyNotify ddestroy = node->destroy;
306
307       node->data = data;
308       node->destroy = notify;
309
310       ddestroy (ddata);
311     }
312   else
313     {
314       node->data = data;
315       node->destroy = notify;
316     }
317 }
318
319 static void
320 g_thread_cleanup (gpointer data)
321 {
322   if (data)
323     {
324       GRealThread* thread = data;
325       if (thread->private_data)
326         {
327           GArray* array = thread->private_data;
328           guint i;
329           
330           for (i = 0; i < array->len; i++ )
331             {
332               GStaticPrivateNode *node = 
333                 &g_array_index (array, GStaticPrivateNode, i);
334               if (node->destroy)
335                 node->destroy (node->data);
336             }
337           g_array_free (array, TRUE);
338         }
339       /* We only free the thread structure, if it isn't joinable. If
340          it is, the structure is freed in g_thread_join */
341       if (!thread->thread.joinable)
342         {
343           /* Just to make sure, this isn't used any more */
344           set_system_thread_to_zero(thread);
345           g_free (thread);
346         }
347     }
348 }
349
350 static void
351 g_thread_fail (void)
352 {
353   g_error ("The thread system is not yet initialized.");
354 }
355
356 G_LOCK_DEFINE_STATIC (g_thread_create);
357
358 static void 
359 g_thread_create_proxy (gpointer data)
360 {
361   GRealThread* thread = data;
362
363   g_assert (data);
364
365   /* the lock makes sure, that thread->system_thread is written,
366      before thread->func is called. See g_thread_create */
367
368   G_LOCK (g_thread_create);
369   g_private_set (g_thread_specific_private, data);
370   G_UNLOCK (g_thread_create);
371
372   thread->func (thread->arg);
373 }
374
375 GThread* 
376 g_thread_create (GThreadFunc             thread_func,
377                  gpointer                arg,
378                  gulong                  stack_size,
379                  gboolean                joinable,
380                  gboolean                bound,
381                  GThreadPriority         priority)
382 {
383   GRealThread* result = g_new0 (GRealThread,1);
384
385   g_return_val_if_fail (thread_func, NULL);
386   
387   result->thread.joinable = joinable;
388   result->thread.bound = bound;
389   result->thread.priority = priority;
390   result->func = thread_func;
391   result->arg = arg;
392   G_LOCK (g_thread_create);
393   G_THREAD_UF (thread_create, (g_thread_create_proxy, result, stack_size, 
394                                joinable, bound, priority,
395                                &result->system_thread));
396   G_UNLOCK (g_thread_create);
397   return (GThread*) result;
398 }
399
400 void 
401 g_thread_join (GThread* thread)
402 {
403   GRealThread* real = (GRealThread*) thread;
404   
405
406   g_return_if_fail (thread);
407   g_return_if_fail (thread->joinable);
408   g_return_if_fail (system_thread_is_not_zero (real));
409
410   G_THREAD_UF (thread_join, (&real->system_thread));
411
412   /* Just to make sure, this isn't used any more */
413   thread->joinable = 0;
414   set_system_thread_to_zero (real);
415
416   /* the thread structure for non-joinable threads is freed upon
417      thread end. We free the memory here. This will leave loose end,
418      if a joinable thread is not joined. */
419
420   g_free (thread);
421 }
422
423 void
424 g_thread_set_priority (GThread* thread, 
425                        GThreadPriority priority)
426 {
427   GRealThread* real = (GRealThread*) thread;
428
429   g_return_if_fail (thread);
430   g_return_if_fail (system_thread_is_not_zero (real));
431
432   thread->priority = priority;
433   G_THREAD_CF (thread_set_priority, (void)0, (&real->system_thread, priority));
434 }
435
436 GThread*
437 g_thread_self()
438 {
439   GRealThread* thread = g_private_get (g_thread_specific_private);
440
441   if (!thread)
442     {  
443       /* If no thread data is available, provide and set one.  This
444          can happen for the main thread and for threads, that are not
445          created by glib. */
446       thread = g_new (GRealThread,1);
447       thread->thread.joinable = FALSE; /* This is a save guess */
448       thread->thread.bound = TRUE; /* This isn't important at all */
449       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
450                                                              just a guess */
451       thread->func = NULL;
452       thread->arg = NULL;
453       set_system_thread_to_zero (thread);
454       thread->private_data = NULL;
455       g_private_set (g_thread_specific_private, thread);
456     }
457      
458   if (g_thread_supported () && !system_thread_is_not_zero(thread))
459     {
460       g_thread_functions_for_glib_use.thread_self(&thread->system_thread);
461     }
462
463   return (GThread*)thread;
464 }
465
466 static void inline g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
467 {
468   if (!*cond)
469       *cond = g_cond_new ();
470   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
471 }
472
473 static void inline g_static_rw_lock_signal (GStaticRWLock* lock)
474 {
475   if (lock->want_to_write && lock->write_cond)
476     g_cond_signal (lock->write_cond);
477   else if (lock->read_cond)
478     g_cond_signal (lock->read_cond);
479 }
480
481 void g_static_rw_lock_reader_lock (GStaticRWLock* lock)
482 {
483   g_return_if_fail (lock);
484
485   if (!g_threads_got_initialized)
486     return;
487
488   g_static_mutex_lock (&lock->mutex);
489   while (lock->write || lock->want_to_write) 
490     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
491   lock->read_counter++;
492   g_static_mutex_unlock (&lock->mutex);
493 }
494
495 gboolean g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
496 {
497   gboolean ret_val = FALSE;
498
499   g_return_val_if_fail (lock, FALSE);
500
501   if (!g_threads_got_initialized)
502     return TRUE;
503
504   g_static_mutex_lock (&lock->mutex);
505   if (!lock->write && !lock->want_to_write)
506     {
507       lock->read_counter++;
508       ret_val = TRUE;
509     }
510   g_static_mutex_unlock (&lock->mutex);
511   return ret_val;
512 }
513
514 void g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
515 {
516   g_return_if_fail (lock);
517
518   if (!g_threads_got_initialized)
519     return;
520
521   g_static_mutex_lock (&lock->mutex);
522   lock->read_counter--;
523   g_static_rw_lock_signal (lock);
524   g_static_mutex_unlock (&lock->mutex);
525 }
526
527 void g_static_rw_lock_writer_lock (GStaticRWLock* lock)
528 {
529   g_return_if_fail (lock);
530
531   if (!g_threads_got_initialized)
532     return;
533
534   g_static_mutex_lock (&lock->mutex);
535   lock->want_to_write++;
536   while (lock->write || lock->read_counter)
537     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
538   lock->want_to_write--;
539   lock->write = TRUE;
540   g_static_mutex_unlock (&lock->mutex);
541 }
542
543 gboolean g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
544 {
545   gboolean ret_val = FALSE;
546
547   g_return_val_if_fail (lock, FALSE);
548   
549   if (!g_threads_got_initialized)
550     return TRUE;
551
552   g_static_mutex_lock (&lock->mutex);
553   if (!lock->write && !lock->read_counter)
554     {
555       lock->write = TRUE;
556       ret_val = TRUE;
557     }
558   g_static_mutex_unlock (&lock->mutex);
559   return ret_val;
560 }
561
562 void g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
563 {
564   g_return_if_fail (lock);
565   
566   if (!g_threads_got_initialized)
567     return;
568
569   g_static_mutex_lock (&lock->mutex);
570   lock->write = FALSE; 
571   g_static_rw_lock_signal (lock);
572   g_static_mutex_unlock (&lock->mutex);
573 }
574
575 void g_static_rw_lock_free (GStaticRWLock* lock)
576 {
577   g_return_if_fail (lock);
578   
579   if (lock->read_cond)
580     g_cond_free (lock->read_cond);
581   if (lock->write_cond)
582     g_cond_free (lock->write_cond);
583   
584 }
585