Added g_static_mutex_init to allow initialization of a GStaticMutex, that
[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_init (GStaticMutex *mutex)
164 {
165   static GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
166
167   g_return_if_fail (mutex);
168
169   memcpy (mutex, &init_mutex, sizeof (GStaticMutex));
170 }
171
172 void
173 g_static_mutex_free (GStaticMutex* mutex)
174 {
175   GMutex **runtime_mutex;
176   
177   g_return_if_fail (mutex);
178
179   /* The runtime_mutex is the first (or only) member of GStaticMutex,
180    * see both versions (of glibconfig.h) in configure.in */
181   runtime_mutex = ((GMutex**)mutex);
182   
183   if (*runtime_mutex)
184     g_mutex_free (*runtime_mutex);
185
186   *runtime_mutex = NULL;
187 }
188
189 void
190 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
191 {
192   GSystemThread self;
193
194   g_return_if_fail (mutex);
195
196   if (!g_thread_supported ())
197     return;
198
199   G_THREAD_UF (thread_self, (&self));
200
201   if (g_system_thread_equal (self, mutex->owner))
202     {
203       mutex->depth++;
204       return;
205     }
206   g_static_mutex_lock (&mutex->mutex);
207   g_system_thread_assign (mutex->owner, self);
208   mutex->depth = 1;
209 }
210
211 gboolean
212 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
213 {
214   GSystemThread self;
215
216   g_return_val_if_fail (mutex, FALSE);
217
218   if (!g_thread_supported ())
219     return TRUE;
220
221   G_THREAD_UF (thread_self, (&self));
222
223   if (g_system_thread_equal (self, mutex->owner))
224     {
225       mutex->depth++;
226       return TRUE;
227     }
228
229   if (!g_static_mutex_trylock (&mutex->mutex))
230     return FALSE;
231
232   g_system_thread_assign (mutex->owner, self);
233   mutex->depth = 1;
234   return TRUE;
235 }
236
237 void
238 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
239 {
240   g_return_if_fail (mutex);
241
242   if (!g_thread_supported ())
243     return;
244
245   if (mutex->depth > 1)
246     {
247       mutex->depth--;
248       return;
249     }
250   g_system_thread_assign (mutex->owner, zero_thread);
251   g_static_mutex_unlock (&mutex->mutex);  
252 }
253
254 void
255 g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
256                                 guint            depth)
257 {
258   g_return_if_fail (mutex);
259
260   if (!g_thread_supported ())
261     return;
262
263   g_static_mutex_lock (&mutex->mutex);
264   G_THREAD_UF (thread_self, (&mutex->owner));
265   mutex->depth = depth;
266 }
267
268 guint    
269 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
270 {
271   gint depth;
272
273   g_return_val_if_fail (mutex, 0);
274
275   if (!g_thread_supported ())
276     return 1;
277
278   depth = mutex->depth;
279
280   g_system_thread_assign (mutex->owner, zero_thread);
281   mutex->depth = 0;
282   g_static_mutex_unlock (&mutex->mutex);
283
284   return depth;
285 }
286
287
288 gpointer
289 g_static_private_get (GStaticPrivate *private_key)
290 {
291   return g_static_private_get_for_thread (private_key, g_thread_self ());
292 }
293
294 gpointer
295 g_static_private_get_for_thread (GStaticPrivate *private_key,
296                                  GThread        *thread)
297 {
298   GArray *array;
299   GRealThread *self = (GRealThread*) thread;
300
301   g_return_val_if_fail (thread, NULL);
302
303   array = self->private_data;
304   if (!array)
305     return NULL;
306
307   if (!private_key->index)
308     return NULL;
309   else if (private_key->index <= array->len)
310     return g_array_index (array, GStaticPrivateNode, private_key->index - 1).data;
311   else
312     return NULL;
313 }
314
315 void
316 g_static_private_set (GStaticPrivate *private_key, 
317                       gpointer        data,
318                       GDestroyNotify  notify)
319 {
320   g_static_private_set_for_thread (private_key, g_thread_self (), 
321                                    data, notify);
322 }
323
324 void
325 g_static_private_set_for_thread (GStaticPrivate *private_key, 
326                                  GThread        *thread,
327                                  gpointer        data,
328                                  GDestroyNotify  notify)
329 {
330   GArray *array;
331   GRealThread *self =(GRealThread*) thread;
332   static guint next_index = 0;
333   GStaticPrivateNode *node;
334
335   g_return_if_fail (thread);
336   
337   array = self->private_data;
338   if (!array)
339     {
340       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
341       self->private_data = array;
342     }
343
344   if (!private_key->index)
345     {
346       g_mutex_lock (g_thread_specific_mutex);
347
348       if (!private_key->index)
349         private_key->index = ++next_index;
350
351       g_mutex_unlock (g_thread_specific_mutex);
352     }
353
354   if (private_key->index > array->len)
355     g_array_set_size (array, private_key->index);
356
357   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
358   if (node->destroy)
359     {
360       gpointer ddata = node->data;
361       GDestroyNotify ddestroy = node->destroy;
362
363       node->data = data;
364       node->destroy = notify;
365
366       ddestroy (ddata);
367     }
368   else
369     {
370       node->data = data;
371       node->destroy = notify;
372     }
373 }
374
375 static void
376 g_thread_cleanup (gpointer data)
377 {
378   if (data)
379     {
380       GRealThread* thread = data;
381       if (thread->private_data)
382         {
383           GArray* array = thread->private_data;
384           guint i;
385           
386           for (i = 0; i < array->len; i++ )
387             {
388               GStaticPrivateNode *node = 
389                 &g_array_index (array, GStaticPrivateNode, i);
390               if (node->destroy)
391                 node->destroy (node->data);
392             }
393           g_array_free (array, TRUE);
394         }
395       /* We only free the thread structure, if it isn't joinable. If
396          it is, the structure is freed in g_thread_join */
397       if (!thread->thread.joinable)
398         {
399           /* Just to make sure, this isn't used any more */
400           g_system_thread_assign (thread->system_thread, zero_thread);
401           g_free (thread);
402         }
403     }
404 }
405
406 static void
407 g_thread_fail (void)
408 {
409   g_error ("The thread system is not yet initialized.");
410 }
411
412 G_LOCK_DEFINE_STATIC (g_thread_create);
413
414 static void 
415 g_thread_create_proxy (gpointer data)
416 {
417   GRealThread* thread = data;
418
419   g_assert (data);
420
421   /* This has to happen before G_LOCK, as that might call g_thread_self */
422   g_private_set (g_thread_specific_private, data);
423
424   /* the lock makes sure, that thread->system_thread is written,
425      before thread->func is called. See g_thread_create. */
426   G_LOCK (g_thread_create);
427   G_UNLOCK (g_thread_create);
428
429   thread->func (thread->arg);
430 }
431
432 GThread* 
433 g_thread_create (GThreadFunc             thread_func,
434                  gpointer                arg,
435                  gulong                  stack_size,
436                  gboolean                joinable,
437                  gboolean                bound,
438                  GThreadPriority         priority,
439                  GError                **error)
440 {
441   GRealThread* result = g_new (GRealThread, 1);
442   GError *local_error = NULL;
443   g_return_val_if_fail (thread_func, NULL);
444   g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
445   g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
446   
447   result->thread.joinable = joinable;
448   result->thread.bound = bound;
449   result->thread.priority = priority;
450   result->func = thread_func;
451   result->arg = arg;
452   result->private_data = NULL; 
453   G_LOCK (g_thread_create);
454   G_THREAD_UF (thread_create, (g_thread_create_proxy, result, 
455                                stack_size, joinable, bound, priority,
456                                &result->system_thread, &local_error));
457   G_UNLOCK (g_thread_create);
458
459   if (local_error)
460     {
461       g_propagate_error (error, local_error);
462       g_free (result);
463       return NULL;
464     }
465
466   return (GThread*) result;
467 }
468
469 void 
470 g_thread_join (GThread* thread)
471 {
472   GRealThread* real = (GRealThread*) thread;
473   
474
475   g_return_if_fail (thread);
476   g_return_if_fail (thread->joinable);
477   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
478
479   G_THREAD_UF (thread_join, (&real->system_thread));
480
481   /* Just to make sure, this isn't used any more */
482   thread->joinable = 0;
483   g_system_thread_assign (real->system_thread, zero_thread);
484
485   /* the thread structure for non-joinable threads is freed upon
486      thread end. We free the memory here. This will leave loose end,
487      if a joinable thread is not joined. */
488
489   g_free (thread);
490 }
491
492 void
493 g_thread_set_priority (GThread* thread, 
494                        GThreadPriority priority)
495 {
496   GRealThread* real = (GRealThread*) thread;
497
498   g_return_if_fail (thread);
499   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
500   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
501   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
502
503   thread->priority = priority;
504   G_THREAD_CF (thread_set_priority, (void)0, (&real->system_thread, priority));
505 }
506
507 GThread*
508 g_thread_self()
509 {
510   GRealThread* thread = g_private_get (g_thread_specific_private);
511
512   if (!thread)
513     {  
514       /* If no thread data is available, provide and set one.  This
515          can happen for the main thread and for threads, that are not
516          created by GLib. */
517       thread = g_new (GRealThread, 1);
518       thread->thread.joinable = FALSE; /* This is a save guess */
519       thread->thread.bound = TRUE; /* This isn't important at all */
520       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
521                                                              just a guess */
522       thread->func = NULL;
523       thread->arg = NULL;
524       thread->private_data = NULL;
525
526       if (g_thread_supported ())
527         G_THREAD_UF (thread_self, (&thread->system_thread));
528
529       g_private_set (g_thread_specific_private, thread);
530     }
531   
532   return (GThread*)thread;
533 }
534
535 static void inline g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
536 {
537   if (!*cond)
538       *cond = g_cond_new ();
539   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
540 }
541
542 static void inline g_static_rw_lock_signal (GStaticRWLock* lock)
543 {
544   if (lock->want_to_write && lock->write_cond)
545     g_cond_signal (lock->write_cond);
546   else if (lock->read_cond)
547     g_cond_broadcast (lock->read_cond);
548 }
549
550 void g_static_rw_lock_reader_lock (GStaticRWLock* lock)
551 {
552   g_return_if_fail (lock);
553
554   if (!g_threads_got_initialized)
555     return;
556
557   g_static_mutex_lock (&lock->mutex);
558   while (lock->write || lock->want_to_write) 
559     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
560   lock->read_counter++;
561   g_static_mutex_unlock (&lock->mutex);
562 }
563
564 gboolean g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
565 {
566   gboolean ret_val = FALSE;
567
568   g_return_val_if_fail (lock, FALSE);
569
570   if (!g_threads_got_initialized)
571     return TRUE;
572
573   g_static_mutex_lock (&lock->mutex);
574   if (!lock->write && !lock->want_to_write)
575     {
576       lock->read_counter++;
577       ret_val = TRUE;
578     }
579   g_static_mutex_unlock (&lock->mutex);
580   return ret_val;
581 }
582
583 void g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
584 {
585   g_return_if_fail (lock);
586
587   if (!g_threads_got_initialized)
588     return;
589
590   g_static_mutex_lock (&lock->mutex);
591   lock->read_counter--;
592   if (lock->read_counter == 0)
593     g_static_rw_lock_signal (lock);
594   g_static_mutex_unlock (&lock->mutex);
595 }
596
597 void g_static_rw_lock_writer_lock (GStaticRWLock* lock)
598 {
599   g_return_if_fail (lock);
600
601   if (!g_threads_got_initialized)
602     return;
603
604   g_static_mutex_lock (&lock->mutex);
605   lock->want_to_write++;
606   while (lock->write || lock->read_counter)
607     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
608   lock->want_to_write--;
609   lock->write = TRUE;
610   g_static_mutex_unlock (&lock->mutex);
611 }
612
613 gboolean g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
614 {
615   gboolean ret_val = FALSE;
616
617   g_return_val_if_fail (lock, FALSE);
618   
619   if (!g_threads_got_initialized)
620     return TRUE;
621
622   g_static_mutex_lock (&lock->mutex);
623   if (!lock->write && !lock->read_counter)
624     {
625       lock->write = TRUE;
626       ret_val = TRUE;
627     }
628   g_static_mutex_unlock (&lock->mutex);
629   return ret_val;
630 }
631
632 void g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
633 {
634   g_return_if_fail (lock);
635   
636   if (!g_threads_got_initialized)
637     return;
638
639   g_static_mutex_lock (&lock->mutex);
640   lock->write = FALSE; 
641   g_static_rw_lock_signal (lock);
642   g_static_mutex_unlock (&lock->mutex);
643 }
644
645 void g_static_rw_lock_free (GStaticRWLock* lock)
646 {
647   g_return_if_fail (lock);
648   
649   if (lock->read_cond)
650     g_cond_free (lock->read_cond);
651   if (lock->write_cond)
652     g_cond_free (lock->write_cond);
653   
654 }
655