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