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