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