Call g_thread_impl_init(), as g_thread_init won't call it.
[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 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 #include "glib.h"
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #if GLIB_SIZEOF_SYSTEM_THREAD == SIZEOF_VOID_P
43 # define g_system_thread_equal(thread1, thread2)                        \
44    (thread1.dummy_pointer == thread2.dummy_pointer)
45 # define g_system_thread_assign(dest, src)                              \
46    (dest.dummy_pointer = src.dummy_pointer)
47 #else /* GLIB_SIZEOF_SYSTEM_THREAD != SIZEOF_VOID_P */
48 # define g_system_thread_equal(thread1, thread2)                        \
49    (memcmp (&thread1, &thread2, GLIB_SIZEOF_SYSTEM_THREAD) == 0)
50 # define g_system_thread_assign(dest, src)                              \
51    (memcpy (&dest, &src, GLIB_SIZEOF_SYSTEM_THREAD))
52 #endif /* GLIB_SIZEOF_SYSTEM_THREAD == SIZEOF_VOID_P */
53
54 GQuark 
55 g_thread_error_quark()
56 {
57   static GQuark quark;
58   if (!quark)
59     quark = g_quark_from_static_string ("g_thread_error");
60   return quark;
61 }
62
63 typedef struct _GRealThread GRealThread;
64 struct  _GRealThread
65 {
66   GThread thread;
67   GThreadFunc func;
68   gpointer arg;
69   gpointer private_data;
70   GSystemThread system_thread;
71 };
72
73 typedef struct _GStaticPrivateNode GStaticPrivateNode;
74 struct _GStaticPrivateNode
75 {
76   gpointer       data;
77   GDestroyNotify destroy;
78 };
79
80 static void g_thread_cleanup (gpointer data);
81 static void g_thread_fail (void);
82
83 /* Global variables */
84
85 static GSystemThread zero_thread; /* This is initialized to all zero */
86 gboolean g_thread_use_default_impl = TRUE;
87 gboolean g_threads_got_initialized = FALSE;
88
89 #if defined(G_OS_WIN32) && defined(__GNUC__)
90 __declspec(dllexport)
91 #endif
92 GThreadFunctions g_thread_functions_for_glib_use = {
93   (GMutex*(*)())g_thread_fail,                 /* mutex_new */
94   NULL,                                        /* mutex_lock */
95   NULL,                                        /* mutex_trylock */
96   NULL,                                        /* mutex_unlock */
97   NULL,                                        /* mutex_free */
98   (GCond*(*)())g_thread_fail,                  /* cond_new */
99   NULL,                                        /* cond_signal */
100   NULL,                                        /* cond_broadcast */
101   NULL,                                        /* cond_wait */
102   NULL,                                        /* cond_timed_wait  */
103   NULL,                                        /* cond_free */
104   (GPrivate*(*)(GDestroyNotify))g_thread_fail, /* private_new */
105   NULL,                                        /* private_get */
106   NULL,                                        /* private_set */
107   (void(*)(GThreadFunc, gpointer, gulong, 
108            gboolean, gboolean, GThreadPriority, 
109            gpointer, GError**))g_thread_fail,  /* thread_create */
110   NULL,                                        /* thread_yield */
111   NULL,                                        /* thread_join */
112   NULL,                                        /* thread_exit */
113   NULL,                                        /* thread_set_priority */
114   NULL                                         /* thread_self */
115 }; 
116
117 /* Local data */
118
119 static GMutex   *g_mutex_protect_static_mutex_allocation = NULL;
120 static GMutex   *g_thread_specific_mutex = NULL;
121 static GPrivate *g_thread_specific_private = NULL;
122
123 /* This must be called only once, before any threads are created.
124  * It will only be called from g_thread_init() in -lgthread.
125  */
126 void
127 g_mutex_init (void)
128 {
129   GRealThread* main_thread;
130  
131   /* We let the main thread (the one that calls g_thread_init) inherit
132    * the data, that it set before calling g_thread_init
133    */
134   main_thread = (GRealThread*) g_thread_self ();
135
136   g_thread_specific_private = g_private_new (g_thread_cleanup);
137   G_THREAD_UF (private_set, (g_thread_specific_private, main_thread));
138   G_THREAD_UF (thread_self, (&main_thread->system_thread));
139
140   g_mutex_protect_static_mutex_allocation = g_mutex_new();
141   g_thread_specific_mutex = g_mutex_new();
142 }
143
144 GMutex *
145 g_static_mutex_get_mutex_impl (GMutex** mutex)
146 {
147   if (!g_thread_supported ())
148     return NULL;
149
150   g_assert (g_mutex_protect_static_mutex_allocation);
151
152   g_mutex_lock (g_mutex_protect_static_mutex_allocation);
153
154   if (!(*mutex)) 
155     *mutex = g_mutex_new(); 
156
157   g_mutex_unlock (g_mutex_protect_static_mutex_allocation);
158   
159   return *mutex;
160 }
161
162 void
163 g_static_mutex_free (GStaticMutex* mutex)
164 {
165   GMutex **runtime_mutex;
166   
167   g_return_if_fail (mutex);
168
169   /* The runtime_mutex is the first (or only) member of GStaticMutex,
170    * see both versions (of glibconfig.h) in configure.in */
171   runtime_mutex = ((GMutex**)mutex);
172   
173   if (*runtime_mutex)
174     g_mutex_free (*runtime_mutex);
175
176   *runtime_mutex = NULL;
177 }
178
179 void
180 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
181 {
182   GSystemThread self;
183
184   g_return_if_fail (mutex);
185
186   if (!g_thread_supported ())
187     return;
188
189   G_THREAD_UF (thread_self, (&self));
190
191   if (g_system_thread_equal (self, mutex->owner))
192     {
193       mutex->depth++;
194       return;
195     }
196   g_static_mutex_lock (&mutex->mutex);
197   g_system_thread_assign (mutex->owner, self);
198   mutex->depth = 1;
199 }
200
201 gboolean
202 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
203 {
204   GSystemThread self;
205
206   g_return_val_if_fail (mutex, FALSE);
207
208   if (!g_thread_supported ())
209     return TRUE;
210
211   G_THREAD_UF (thread_self, (&self));
212
213   if (g_system_thread_equal (self, mutex->owner))
214     {
215       mutex->depth++;
216       return TRUE;
217     }
218
219   if (!g_static_mutex_trylock (&mutex->mutex))
220     return FALSE;
221
222   g_system_thread_assign (mutex->owner, self);
223   mutex->depth = 1;
224   return TRUE;
225 }
226
227 void
228 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
229 {
230   g_return_if_fail (mutex);
231
232   if (!g_thread_supported ())
233     return;
234
235   if (mutex->depth > 1)
236     {
237       mutex->depth--;
238       return;
239     }
240   g_system_thread_assign (mutex->owner, zero_thread);
241   g_static_mutex_unlock (&mutex->mutex);  
242 }
243
244 void
245 g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
246                                 guint            depth)
247 {
248   g_return_if_fail (mutex);
249
250   if (!g_thread_supported ())
251     return;
252
253   g_static_mutex_lock (&mutex->mutex);
254   G_THREAD_UF (thread_self, (&mutex->owner));
255   mutex->depth = depth;
256 }
257
258 guint    
259 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
260 {
261   gint depth;
262
263   g_return_val_if_fail (mutex, 0);
264
265   if (!g_thread_supported ())
266     return 1;
267
268   depth = mutex->depth;
269
270   g_system_thread_assign (mutex->owner, zero_thread);
271   mutex->depth = 0;
272   g_static_mutex_unlock (&mutex->mutex);
273
274   return depth;
275 }
276
277
278 gpointer
279 g_static_private_get (GStaticPrivate *private_key)
280 {
281   return g_static_private_get_for_thread (private_key, g_thread_self ());
282 }
283
284 gpointer
285 g_static_private_get_for_thread (GStaticPrivate *private_key,
286                                  GThread        *thread)
287 {
288   GArray *array;
289   GRealThread *self = (GRealThread*) thread;
290
291   g_return_val_if_fail (thread, NULL);
292
293   array = self->private_data;
294   if (!array)
295     return NULL;
296
297   if (!private_key->index)
298     return NULL;
299   else if (private_key->index <= array->len)
300     return g_array_index (array, GStaticPrivateNode, private_key->index - 1).data;
301   else
302     return NULL;
303 }
304
305 void
306 g_static_private_set (GStaticPrivate *private_key, 
307                       gpointer        data,
308                       GDestroyNotify  notify)
309 {
310   g_static_private_set_for_thread (private_key, g_thread_self (), 
311                                    data, notify);
312 }
313
314 void
315 g_static_private_set_for_thread (GStaticPrivate *private_key, 
316                                  GThread        *thread,
317                                  gpointer        data,
318                                  GDestroyNotify  notify)
319 {
320   GArray *array;
321   GRealThread *self =(GRealThread*) thread;
322   static guint next_index = 0;
323   GStaticPrivateNode *node;
324
325   g_return_if_fail (thread);
326   
327   array = self->private_data;
328   if (!array)
329     {
330       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
331       self->private_data = array;
332     }
333
334   if (!private_key->index)
335     {
336       g_mutex_lock (g_thread_specific_mutex);
337
338       if (!private_key->index)
339         private_key->index = ++next_index;
340
341       g_mutex_unlock (g_thread_specific_mutex);
342     }
343
344   if (private_key->index > array->len)
345     g_array_set_size (array, private_key->index);
346
347   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
348   if (node->destroy)
349     {
350       gpointer ddata = node->data;
351       GDestroyNotify ddestroy = node->destroy;
352
353       node->data = data;
354       node->destroy = notify;
355
356       ddestroy (ddata);
357     }
358   else
359     {
360       node->data = data;
361       node->destroy = notify;
362     }
363 }
364
365 static void
366 g_thread_cleanup (gpointer data)
367 {
368   if (data)
369     {
370       GRealThread* thread = data;
371       if (thread->private_data)
372         {
373           GArray* array = thread->private_data;
374           guint i;
375           
376           for (i = 0; i < array->len; i++ )
377             {
378               GStaticPrivateNode *node = 
379                 &g_array_index (array, GStaticPrivateNode, i);
380               if (node->destroy)
381                 node->destroy (node->data);
382             }
383           g_array_free (array, TRUE);
384         }
385       /* We only free the thread structure, if it isn't joinable. If
386          it is, the structure is freed in g_thread_join */
387       if (!thread->thread.joinable)
388         {
389           /* Just to make sure, this isn't used any more */
390           g_system_thread_assign (thread->system_thread, zero_thread);
391           g_free (thread);
392         }
393     }
394 }
395
396 static void
397 g_thread_fail (void)
398 {
399   g_error ("The thread system is not yet initialized.");
400 }
401
402 G_LOCK_DEFINE_STATIC (g_thread_create);
403
404 static void 
405 g_thread_create_proxy (gpointer data)
406 {
407   GRealThread* thread = data;
408
409   g_assert (data);
410
411   /* This has to happen before G_LOCK, as that might call g_thread_self */
412   g_private_set (g_thread_specific_private, data);
413
414   /* the lock makes sure, that thread->system_thread is written,
415      before thread->func is called. See g_thread_create. */
416   G_LOCK (g_thread_create);
417   G_UNLOCK (g_thread_create);
418
419   thread->func (thread->arg);
420 }
421
422 GThread* 
423 g_thread_create (GThreadFunc             thread_func,
424                  gpointer                arg,
425                  gulong                  stack_size,
426                  gboolean                joinable,
427                  gboolean                bound,
428                  GThreadPriority         priority,
429                  GError                **error)
430 {
431   GRealThread* result = g_new (GRealThread, 1);
432   GError *local_error = NULL;
433   g_return_val_if_fail (thread_func, NULL);
434   g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
435   g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
436   
437   result->thread.joinable = joinable;
438   result->thread.bound = bound;
439   result->thread.priority = priority;
440   result->func = thread_func;
441   result->arg = arg;
442   result->private_data = NULL; 
443   G_LOCK (g_thread_create);
444   G_THREAD_UF (thread_create, (g_thread_create_proxy, result, 
445                                stack_size, joinable, bound, priority,
446                                &result->system_thread, &local_error));
447   G_UNLOCK (g_thread_create);
448
449   if (local_error)
450     {
451       g_propagate_error (error, local_error);
452       g_free (result);
453       return NULL;
454     }
455
456   return (GThread*) result;
457 }
458
459 void 
460 g_thread_join (GThread* thread)
461 {
462   GRealThread* real = (GRealThread*) thread;
463   
464
465   g_return_if_fail (thread);
466   g_return_if_fail (thread->joinable);
467   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
468
469   G_THREAD_UF (thread_join, (&real->system_thread));
470
471   /* Just to make sure, this isn't used any more */
472   thread->joinable = 0;
473   g_system_thread_assign (real->system_thread, zero_thread);
474
475   /* the thread structure for non-joinable threads is freed upon
476      thread end. We free the memory here. This will leave loose end,
477      if a joinable thread is not joined. */
478
479   g_free (thread);
480 }
481
482 void
483 g_thread_set_priority (GThread* thread, 
484                        GThreadPriority priority)
485 {
486   GRealThread* real = (GRealThread*) thread;
487
488   g_return_if_fail (thread);
489   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
490   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
491   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
492
493   thread->priority = priority;
494   G_THREAD_CF (thread_set_priority, (void)0, (&real->system_thread, priority));
495 }
496
497 GThread*
498 g_thread_self()
499 {
500   GRealThread* thread = g_private_get (g_thread_specific_private);
501
502   if (!thread)
503     {  
504       /* If no thread data is available, provide and set one.  This
505          can happen for the main thread and for threads, that are not
506          created by GLib. */
507       thread = g_new (GRealThread, 1);
508       thread->thread.joinable = FALSE; /* This is a save guess */
509       thread->thread.bound = TRUE; /* This isn't important at all */
510       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
511                                                              just a guess */
512       thread->func = NULL;
513       thread->arg = NULL;
514       thread->private_data = NULL;
515
516       if (g_thread_supported ())
517         G_THREAD_UF (thread_self, (&thread->system_thread));
518
519       g_private_set (g_thread_specific_private, thread);
520     }
521   
522   return (GThread*)thread;
523 }
524
525 static void inline g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
526 {
527   if (!*cond)
528       *cond = g_cond_new ();
529   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
530 }
531
532 static void inline g_static_rw_lock_signal (GStaticRWLock* lock)
533 {
534   if (lock->want_to_write && lock->write_cond)
535     g_cond_signal (lock->write_cond);
536   else if (lock->read_cond)
537     g_cond_broadcast (lock->read_cond);
538 }
539
540 void g_static_rw_lock_reader_lock (GStaticRWLock* lock)
541 {
542   g_return_if_fail (lock);
543
544   if (!g_threads_got_initialized)
545     return;
546
547   g_static_mutex_lock (&lock->mutex);
548   while (lock->write || lock->want_to_write) 
549     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
550   lock->read_counter++;
551   g_static_mutex_unlock (&lock->mutex);
552 }
553
554 gboolean g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
555 {
556   gboolean ret_val = FALSE;
557
558   g_return_val_if_fail (lock, FALSE);
559
560   if (!g_threads_got_initialized)
561     return TRUE;
562
563   g_static_mutex_lock (&lock->mutex);
564   if (!lock->write && !lock->want_to_write)
565     {
566       lock->read_counter++;
567       ret_val = TRUE;
568     }
569   g_static_mutex_unlock (&lock->mutex);
570   return ret_val;
571 }
572
573 void g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
574 {
575   g_return_if_fail (lock);
576
577   if (!g_threads_got_initialized)
578     return;
579
580   g_static_mutex_lock (&lock->mutex);
581   lock->read_counter--;
582   if (lock->read_counter == 0)
583     g_static_rw_lock_signal (lock);
584   g_static_mutex_unlock (&lock->mutex);
585 }
586
587 void g_static_rw_lock_writer_lock (GStaticRWLock* lock)
588 {
589   g_return_if_fail (lock);
590
591   if (!g_threads_got_initialized)
592     return;
593
594   g_static_mutex_lock (&lock->mutex);
595   lock->want_to_write++;
596   while (lock->write || lock->read_counter)
597     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
598   lock->want_to_write--;
599   lock->write = TRUE;
600   g_static_mutex_unlock (&lock->mutex);
601 }
602
603 gboolean g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
604 {
605   gboolean ret_val = FALSE;
606
607   g_return_val_if_fail (lock, FALSE);
608   
609   if (!g_threads_got_initialized)
610     return TRUE;
611
612   g_static_mutex_lock (&lock->mutex);
613   if (!lock->write && !lock->read_counter)
614     {
615       lock->write = TRUE;
616       ret_val = TRUE;
617     }
618   g_static_mutex_unlock (&lock->mutex);
619   return ret_val;
620 }
621
622 void g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
623 {
624   g_return_if_fail (lock);
625   
626   if (!g_threads_got_initialized)
627     return;
628
629   g_static_mutex_lock (&lock->mutex);
630   lock->write = FALSE; 
631   g_static_rw_lock_signal (lock);
632   g_static_mutex_unlock (&lock->mutex);
633 }
634
635 void g_static_rw_lock_free (GStaticRWLock* lock)
636 {
637   g_return_if_fail (lock);
638   
639   if (lock->read_cond)
640     g_cond_free (lock->read_cond);
641   if (lock->write_cond)
642     g_cond_free (lock->write_cond);
643   
644 }
645