Added functions g_static_rec_mutex_init, g_static_rec_mutex_free,
[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 (void)
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 GPrivate *g_thread_specific_private = NULL;
121 static GSList   *g_thread_all_threads = NULL;
122 static GSList   *g_thread_free_indeces = NULL;
123
124 G_LOCK_DEFINE_STATIC (g_thread);
125
126 /* This must be called only once, before any threads are created.
127  * It will only be called from g_thread_init() in -lgthread.
128  */
129 void
130 g_mutex_init (void)
131 {
132   GRealThread* main_thread;
133  
134   /* We let the main thread (the one that calls g_thread_init) inherit
135    * the data, that it set before calling g_thread_init
136    */
137   main_thread = (GRealThread*) g_thread_self ();
138
139   g_thread_specific_private = g_private_new (g_thread_cleanup);
140   G_THREAD_UF (private_set, (g_thread_specific_private, main_thread));
141   G_THREAD_UF (thread_self, (&main_thread->system_thread));
142
143   g_mutex_protect_static_mutex_allocation = g_mutex_new ();
144 }
145
146 void 
147 g_static_mutex_init (GStaticMutex *mutex)
148 {
149   static GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
150
151   g_return_if_fail (mutex);
152
153   memcpy (mutex, &init_mutex, sizeof (GStaticMutex));
154 }
155
156 GMutex *
157 g_static_mutex_get_mutex_impl (GMutex** mutex)
158 {
159   if (!g_thread_supported ())
160     return NULL;
161
162   g_assert (g_mutex_protect_static_mutex_allocation);
163
164   g_mutex_lock (g_mutex_protect_static_mutex_allocation);
165
166   if (!(*mutex)) 
167     *mutex = g_mutex_new (); 
168
169   g_mutex_unlock (g_mutex_protect_static_mutex_allocation);
170   
171   return *mutex;
172 }
173
174 void
175 g_static_mutex_free (GStaticMutex* mutex)
176 {
177   GMutex **runtime_mutex;
178   
179   g_return_if_fail (mutex);
180
181   /* The runtime_mutex is the first (or only) member of GStaticMutex,
182    * see both versions (of glibconfig.h) in configure.in */
183   runtime_mutex = ((GMutex**)mutex);
184   
185   if (*runtime_mutex)
186     g_mutex_free (*runtime_mutex);
187
188   *runtime_mutex = NULL;
189 }
190
191 void     
192 g_static_rec_mutex_init (GStaticRecMutex *mutex)
193 {
194   static GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
195   
196   g_return_if_fail (mutex);
197
198   memcpy (mutex, &init_mutex, sizeof (GStaticRecMutex));
199 }
200
201 void
202 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
203 {
204   GSystemThread self;
205
206   g_return_if_fail (mutex);
207
208   if (!g_thread_supported ())
209     return;
210
211   G_THREAD_UF (thread_self, (&self));
212
213   if (g_system_thread_equal (self, mutex->owner))
214     {
215       mutex->depth++;
216       return;
217     }
218   g_static_mutex_lock (&mutex->mutex);
219   g_system_thread_assign (mutex->owner, self);
220   mutex->depth = 1;
221 }
222
223 gboolean
224 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
225 {
226   GSystemThread self;
227
228   g_return_val_if_fail (mutex, FALSE);
229
230   if (!g_thread_supported ())
231     return TRUE;
232
233   G_THREAD_UF (thread_self, (&self));
234
235   if (g_system_thread_equal (self, mutex->owner))
236     {
237       mutex->depth++;
238       return TRUE;
239     }
240
241   if (!g_static_mutex_trylock (&mutex->mutex))
242     return FALSE;
243
244   g_system_thread_assign (mutex->owner, self);
245   mutex->depth = 1;
246   return TRUE;
247 }
248
249 void
250 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
251 {
252   g_return_if_fail (mutex);
253
254   if (!g_thread_supported ())
255     return;
256
257   if (mutex->depth > 1)
258     {
259       mutex->depth--;
260       return;
261     }
262   g_system_thread_assign (mutex->owner, zero_thread);
263   g_static_mutex_unlock (&mutex->mutex);  
264 }
265
266 void
267 g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
268                                 guint            depth)
269 {
270   g_return_if_fail (mutex);
271
272   if (!g_thread_supported ())
273     return;
274
275   g_static_mutex_lock (&mutex->mutex);
276   G_THREAD_UF (thread_self, (&mutex->owner));
277   mutex->depth = depth;
278 }
279
280 guint    
281 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
282 {
283   gint depth;
284
285   g_return_val_if_fail (mutex, 0);
286
287   if (!g_thread_supported ())
288     return 1;
289
290   depth = mutex->depth;
291
292   g_system_thread_assign (mutex->owner, zero_thread);
293   mutex->depth = 0;
294   g_static_mutex_unlock (&mutex->mutex);
295
296   return depth;
297 }
298
299 void
300 g_static_rec_mutex_free (GStaticRecMutex *mutex)
301 {
302   g_return_if_fail (mutex);
303
304   g_static_mutex_free (&mutex->mutex);
305 }
306
307 void     
308 g_static_private_init (GStaticPrivate *private_key)
309 {
310   private_key->index = 0;
311 }
312
313 gpointer
314 g_static_private_get (GStaticPrivate *private_key)
315 {
316   return g_static_private_get_for_thread (private_key, g_thread_self ());
317 }
318
319 gpointer
320 g_static_private_get_for_thread (GStaticPrivate *private_key,
321                                  GThread        *thread)
322 {
323   GArray *array;
324   GRealThread *self = (GRealThread*) thread;
325
326   g_return_val_if_fail (thread, NULL);
327
328   array = self->private_data;
329   if (!array)
330     return NULL;
331
332   if (!private_key->index)
333     return NULL;
334   else if (private_key->index <= array->len)
335     return g_array_index (array, GStaticPrivateNode, private_key->index - 1).data;
336   else
337     return NULL;
338 }
339
340 void
341 g_static_private_set (GStaticPrivate *private_key, 
342                       gpointer        data,
343                       GDestroyNotify  notify)
344 {
345   g_static_private_set_for_thread (private_key, g_thread_self (), 
346                                    data, notify);
347 }
348
349 void
350 g_static_private_set_for_thread (GStaticPrivate *private_key, 
351                                  GThread        *thread,
352                                  gpointer        data,
353                                  GDestroyNotify  notify)
354 {
355   GArray *array;
356   GRealThread *self =(GRealThread*) thread;
357   static guint next_index = 0;
358   GStaticPrivateNode *node;
359
360   g_return_if_fail (thread);
361   
362   array = self->private_data;
363   if (!array)
364     {
365       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
366       self->private_data = array;
367     }
368
369   if (!private_key->index)
370     {
371       G_LOCK (g_thread);
372
373       if (!private_key->index)
374         {
375           if (g_thread_free_indeces)
376             {
377               private_key->index = 
378                 GPOINTER_TO_UINT (g_thread_free_indeces->data);
379               g_thread_free_indeces = 
380                 g_slist_delete_link (g_thread_free_indeces,
381                                      g_thread_free_indeces);
382             }
383           else
384             private_key->index = ++next_index;
385         }
386
387       G_UNLOCK (g_thread);
388     }
389
390   if (private_key->index > array->len)
391     g_array_set_size (array, private_key->index);
392
393   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
394   if (node->destroy)
395     {
396       gpointer ddata = node->data;
397       GDestroyNotify ddestroy = node->destroy;
398
399       node->data = data;
400       node->destroy = notify;
401
402       ddestroy (ddata);
403     }
404   else
405     {
406       node->data = data;
407       node->destroy = notify;
408     }
409 }
410
411 void     
412 g_static_private_free (GStaticPrivate *private_key)
413 {
414   GStaticPrivate copied_key;
415   GSList *list;
416
417   copied_key.index = private_key->index;
418   private_key->index = 0;
419
420   if (!copied_key.index)
421     return;
422
423   G_LOCK (g_thread);
424   list =  g_thread_all_threads;
425   while (list)
426     {
427       GThread *thread = list->data;
428       list = list->next;
429       
430       G_UNLOCK (g_thread);
431       g_static_private_set_for_thread (&copied_key, thread, NULL, NULL);
432       G_LOCK (g_thread);
433     }
434   g_thread_free_indeces = 
435     g_slist_prepend (g_thread_free_indeces, 
436                      GUINT_TO_POINTER (copied_key.index));
437   G_UNLOCK (g_thread);
438 }
439
440 static void
441 g_thread_cleanup (gpointer data)
442 {
443   if (data)
444     {
445       GRealThread* thread = data;
446       if (thread->private_data)
447         {
448           GArray* array = thread->private_data;
449           guint i;
450           
451           for (i = 0; i < array->len; i++ )
452             {
453               GStaticPrivateNode *node = 
454                 &g_array_index (array, GStaticPrivateNode, i);
455               if (node->destroy)
456                 node->destroy (node->data);
457             }
458           g_array_free (array, TRUE);
459         }
460       /* We only free the thread structure, if it isn't joinable. If
461          it is, the structure is freed in g_thread_join */
462       if (!thread->thread.joinable)
463         {
464           G_LOCK (g_thread);
465           g_thread_all_threads = g_slist_remove (g_thread_all_threads, data);
466           G_UNLOCK (g_thread);
467           
468           /* Just to make sure, this isn't used any more */
469           g_system_thread_assign (thread->system_thread, zero_thread);
470           g_free (thread);
471         }
472     }
473 }
474
475 static void
476 g_thread_fail (void)
477 {
478   g_error ("The thread system is not yet initialized.");
479 }
480
481 static void 
482 g_thread_create_proxy (gpointer data)
483 {
484   GRealThread* thread = data;
485
486   g_assert (data);
487
488   /* This has to happen before G_LOCK, as that might call g_thread_self */
489   g_private_set (g_thread_specific_private, data);
490
491   /* the lock makes sure, that thread->system_thread is written,
492      before thread->func is called. See g_thread_create. */
493   G_LOCK (g_thread);
494   G_UNLOCK (g_thread);
495
496   thread->func (thread->arg);
497 }
498
499 GThread* 
500 g_thread_create (GThreadFunc             thread_func,
501                  gpointer                arg,
502                  gulong                  stack_size,
503                  gboolean                joinable,
504                  gboolean                bound,
505                  GThreadPriority         priority,
506                  GError                **error)
507 {
508   GRealThread* result = g_new (GRealThread, 1);
509   GError *local_error = NULL;
510   g_return_val_if_fail (thread_func, NULL);
511   g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
512   g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
513   
514   result->thread.joinable = joinable;
515   result->thread.bound = bound;
516   result->thread.priority = priority;
517   result->func = thread_func;
518   result->arg = arg;
519   result->private_data = NULL; 
520   G_LOCK (g_thread);
521   G_THREAD_UF (thread_create, (g_thread_create_proxy, result, 
522                                stack_size, joinable, bound, priority,
523                                &result->system_thread, &local_error));
524   g_thread_all_threads = g_slist_prepend (g_thread_all_threads, result);
525   G_UNLOCK (g_thread);
526
527   if (local_error)
528     {
529       g_propagate_error (error, local_error);
530       g_free (result);
531       return NULL;
532     }
533
534   return (GThread*) result;
535 }
536
537 void 
538 g_thread_join (GThread* thread)
539 {
540   GRealThread* real = (GRealThread*) thread;
541   
542
543   g_return_if_fail (thread);
544   g_return_if_fail (thread->joinable);
545   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
546
547   G_THREAD_UF (thread_join, (&real->system_thread));
548
549   G_LOCK (g_thread);
550   g_thread_all_threads = g_slist_remove (g_thread_all_threads, thread);
551   G_UNLOCK (g_thread);
552
553   /* Just to make sure, this isn't used any more */
554   thread->joinable = 0;
555   g_system_thread_assign (real->system_thread, zero_thread);
556
557   /* the thread structure for non-joinable threads is freed upon
558      thread end. We free the memory here. This will leave loose end,
559      if a joinable thread is not joined. */
560
561   g_free (thread);
562 }
563
564 void
565 g_thread_set_priority (GThread* thread, 
566                        GThreadPriority priority)
567 {
568   GRealThread* real = (GRealThread*) thread;
569
570   g_return_if_fail (thread);
571   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
572   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
573   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
574
575   thread->priority = priority;
576   G_THREAD_CF (thread_set_priority, (void)0, (&real->system_thread, priority));
577 }
578
579 GThread*
580 g_thread_self (void)
581 {
582   GRealThread* thread = g_private_get (g_thread_specific_private);
583
584   if (!thread)
585     {  
586       /* If no thread data is available, provide and set one.  This
587          can happen for the main thread and for threads, that are not
588          created by GLib. */
589       thread = g_new (GRealThread, 1);
590       thread->thread.joinable = FALSE; /* This is a save guess */
591       thread->thread.bound = TRUE; /* This isn't important at all */
592       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
593                                                              just a guess */
594       thread->func = NULL;
595       thread->arg = NULL;
596       thread->private_data = NULL;
597
598       if (g_thread_supported ())
599         G_THREAD_UF (thread_self, (&thread->system_thread));
600
601       g_private_set (g_thread_specific_private, thread); 
602       
603       G_LOCK (g_thread);
604       g_thread_all_threads = g_slist_prepend (g_thread_all_threads, thread);
605       G_UNLOCK (g_thread);
606     }
607   
608   return (GThread*)thread;
609 }
610
611 void
612 g_static_rw_lock_init (GStaticRWLock* lock)
613 {
614   static GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
615
616   g_return_if_fail (lock);
617
618   memcpy (lock, &init_lock, sizeof (GStaticRWLock));
619 }
620
621 static void inline 
622 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
623 {
624   if (!*cond)
625       *cond = g_cond_new ();
626   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
627 }
628
629 static void inline 
630 g_static_rw_lock_signal (GStaticRWLock* lock)
631 {
632   if (lock->want_to_write && lock->write_cond)
633     g_cond_signal (lock->write_cond);
634   else if (lock->read_cond)
635     g_cond_broadcast (lock->read_cond);
636 }
637
638 void 
639 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
640 {
641   g_return_if_fail (lock);
642
643   if (!g_threads_got_initialized)
644     return;
645
646   g_static_mutex_lock (&lock->mutex);
647   while (lock->write || lock->want_to_write) 
648     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
649   lock->read_counter++;
650   g_static_mutex_unlock (&lock->mutex);
651 }
652
653 gboolean 
654 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
655 {
656   gboolean ret_val = FALSE;
657
658   g_return_val_if_fail (lock, FALSE);
659
660   if (!g_threads_got_initialized)
661     return TRUE;
662
663   g_static_mutex_lock (&lock->mutex);
664   if (!lock->write && !lock->want_to_write)
665     {
666       lock->read_counter++;
667       ret_val = TRUE;
668     }
669   g_static_mutex_unlock (&lock->mutex);
670   return ret_val;
671 }
672
673 void 
674 g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
675 {
676   g_return_if_fail (lock);
677
678   if (!g_threads_got_initialized)
679     return;
680
681   g_static_mutex_lock (&lock->mutex);
682   lock->read_counter--;
683   if (lock->read_counter == 0)
684     g_static_rw_lock_signal (lock);
685   g_static_mutex_unlock (&lock->mutex);
686 }
687
688 void 
689 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
690 {
691   g_return_if_fail (lock);
692
693   if (!g_threads_got_initialized)
694     return;
695
696   g_static_mutex_lock (&lock->mutex);
697   lock->want_to_write++;
698   while (lock->write || lock->read_counter)
699     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
700   lock->want_to_write--;
701   lock->write = TRUE;
702   g_static_mutex_unlock (&lock->mutex);
703 }
704
705 gboolean 
706 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
707 {
708   gboolean ret_val = FALSE;
709
710   g_return_val_if_fail (lock, FALSE);
711   
712   if (!g_threads_got_initialized)
713     return TRUE;
714
715   g_static_mutex_lock (&lock->mutex);
716   if (!lock->write && !lock->read_counter)
717     {
718       lock->write = TRUE;
719       ret_val = TRUE;
720     }
721   g_static_mutex_unlock (&lock->mutex);
722   return ret_val;
723 }
724
725 void 
726 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
727 {
728   g_return_if_fail (lock);
729   
730   if (!g_threads_got_initialized)
731     return;
732
733   g_static_mutex_lock (&lock->mutex);
734   lock->write = FALSE; 
735   g_static_rw_lock_signal (lock);
736   g_static_mutex_unlock (&lock->mutex);
737 }
738
739 void 
740 g_static_rw_lock_free (GStaticRWLock* lock)
741 {
742   g_return_if_fail (lock);
743   
744   if (lock->read_cond)
745     {
746       g_cond_free (lock->read_cond);
747       lock->read_cond = NULL;
748     }
749   if (lock->write_cond)
750     {
751       g_cond_free (lock->write_cond);
752       lock->write_cond = NULL;
753     }
754   g_static_mutex_free (&lock->mutex);
755 }