Bug 548967 - 1 bit mutex lock
[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  * gthread.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 /* implement gthread.h's inline functions */
36 #define G_IMPLEMENT_INLINES 1
37 #define __G_THREAD_C__
38
39 #include "config.h"
40
41 #include "glib.h"
42 #include "gthreadprivate.h"
43
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
47
48 #ifndef G_OS_WIN32
49 #include <sys/time.h>
50 #include <time.h>
51 #else
52 #include <windows.h>
53 #endif /* G_OS_WIN32 */
54
55 #include <string.h>
56
57 #include "galias.h"
58
59 GQuark
60 g_thread_error_quark (void)
61 {
62   return g_quark_from_static_string ("g_thread_error");
63 }
64
65 /* Keep this in sync with GRealThread in gmain.c! */
66 typedef struct _GRealThread GRealThread;
67 struct  _GRealThread
68 {
69   GThread thread;
70   gpointer private_data;
71   GRealThread *next;
72   gpointer retval;
73   GSystemThread system_thread;
74 };
75
76 typedef struct _GStaticPrivateNode GStaticPrivateNode;
77 struct _GStaticPrivateNode
78 {
79   gpointer       data;
80   GDestroyNotify destroy;
81 };
82
83 static void    g_thread_cleanup (gpointer data);
84 static void    g_thread_fail (void);
85 static guint64 gettime (void);
86
87 guint64        (*g_thread_gettime) (void) = gettime;
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 GThreadFunctions g_thread_functions_for_glib_use = {
96   (GMutex*(*)())g_thread_fail,                 /* mutex_new */
97   NULL,                                        /* mutex_lock */
98   NULL,                                        /* mutex_trylock */
99   NULL,                                        /* mutex_unlock */
100   NULL,                                        /* mutex_free */
101   (GCond*(*)())g_thread_fail,                  /* cond_new */
102   NULL,                                        /* cond_signal */
103   NULL,                                        /* cond_broadcast */
104   NULL,                                        /* cond_wait */
105   NULL,                                        /* cond_timed_wait  */
106   NULL,                                        /* cond_free */
107   (GPrivate*(*)(GDestroyNotify))g_thread_fail, /* private_new */
108   NULL,                                        /* private_get */
109   NULL,                                        /* private_set */
110   (void(*)(GThreadFunc, gpointer, gulong,
111            gboolean, gboolean, GThreadPriority,
112            gpointer, GError**))g_thread_fail,  /* thread_create */
113   NULL,                                        /* thread_yield */
114   NULL,                                        /* thread_join */
115   NULL,                                        /* thread_exit */
116   NULL,                                        /* thread_set_priority */
117   NULL,                                        /* thread_self */
118   NULL                                         /* thread_equal */
119 };
120
121 /* Local data */
122
123 static GMutex   *g_once_mutex = NULL;
124 static GCond    *g_once_cond = NULL;
125 static GPrivate *g_thread_specific_private = NULL;
126 static GRealThread *g_thread_all_threads = NULL;
127 static GSList   *g_thread_free_indeces = NULL;
128 static GSList*   g_once_init_list = NULL;
129
130 G_LOCK_DEFINE_STATIC (g_thread);
131
132 #ifdef G_THREADS_ENABLED
133 /* This must be called only once, before any threads are created.
134  * It will only be called from g_thread_init() in -lgthread.
135  */
136 void
137 g_thread_init_glib (void)
138 {
139   /* We let the main thread (the one that calls g_thread_init) inherit
140    * the static_private data set before calling g_thread_init
141    */
142   GRealThread* main_thread = (GRealThread*) g_thread_self ();
143
144   /* mutex and cond creation works without g_threads_got_initialized */
145   g_once_mutex = g_mutex_new ();
146   g_once_cond = g_cond_new ();
147
148   /* we may only create mutex and cond in here */
149   _g_mem_thread_init_noprivate_nomessage ();
150
151   /* setup the basic threading system */
152   g_threads_got_initialized = TRUE;
153   g_thread_specific_private = g_private_new (g_thread_cleanup);
154   g_private_set (g_thread_specific_private, main_thread);
155   G_THREAD_UF (thread_self, (&main_thread->system_thread));
156
157   /* complete memory system initialization, g_private_*() works now */
158   _g_slice_thread_init_nomessage ();
159
160   /* accomplish log system initialization to enable messaging */
161   _g_messages_thread_init_nomessage ();
162
163   /* we may run full-fledged initializers from here */
164   _g_atomic_thread_init ();
165   _g_convert_thread_init ();
166   _g_rand_thread_init ();
167   _g_main_thread_init ();
168   _g_utils_thread_init ();
169   _g_futex_thread_init ();
170 #ifdef G_OS_WIN32
171   _g_win32_thread_init ();
172 #endif
173 }
174 #endif /* G_THREADS_ENABLED */
175
176 gpointer
177 g_once_impl (GOnce       *once,
178              GThreadFunc  func,
179              gpointer     arg)
180 {
181   g_mutex_lock (g_once_mutex);
182
183   while (once->status == G_ONCE_STATUS_PROGRESS)
184     g_cond_wait (g_once_cond, g_once_mutex);
185
186   if (once->status != G_ONCE_STATUS_READY)
187     {
188       once->status = G_ONCE_STATUS_PROGRESS;
189       g_mutex_unlock (g_once_mutex);
190
191       once->retval = func (arg);
192
193       g_mutex_lock (g_once_mutex);
194       once->status = G_ONCE_STATUS_READY;
195       g_cond_broadcast (g_once_cond);
196     }
197
198   g_mutex_unlock (g_once_mutex);
199
200   return once->retval;
201 }
202
203 gboolean
204 g_once_init_enter_impl (volatile gsize *value_location)
205 {
206   gboolean need_init = FALSE;
207   g_mutex_lock (g_once_mutex);
208   if (g_atomic_pointer_get (value_location) == NULL)
209     {
210       if (!g_slist_find (g_once_init_list, (void*) value_location))
211         {
212           need_init = TRUE;
213           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
214         }
215       else
216         do
217           g_cond_wait (g_once_cond, g_once_mutex);
218         while (g_slist_find (g_once_init_list, (void*) value_location));
219     }
220   g_mutex_unlock (g_once_mutex);
221   return need_init;
222 }
223
224 void
225 g_once_init_leave (volatile gsize *value_location,
226                    gsize           initialization_value)
227 {
228   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
229   g_return_if_fail (initialization_value != 0);
230   g_return_if_fail (g_once_init_list != NULL);
231
232   g_atomic_pointer_set ((void**)value_location, (void*) initialization_value);
233   g_mutex_lock (g_once_mutex);
234   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
235   g_cond_broadcast (g_once_cond);
236   g_mutex_unlock (g_once_mutex);
237 }
238
239 void
240 g_static_mutex_init (GStaticMutex *mutex)
241 {
242   static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
243
244   g_return_if_fail (mutex);
245
246   *mutex = init_mutex;
247 }
248
249 GMutex *
250 g_static_mutex_get_mutex_impl (GMutex** mutex)
251 {
252   if (!g_thread_supported ())
253     return NULL;
254
255   g_assert (g_once_mutex);
256
257   g_mutex_lock (g_once_mutex);
258
259   if (!(*mutex))
260     g_atomic_pointer_set (mutex, g_mutex_new());
261
262   g_mutex_unlock (g_once_mutex);
263
264   return *mutex;
265 }
266
267 void
268 g_static_mutex_free (GStaticMutex* mutex)
269 {
270   GMutex **runtime_mutex;
271
272   g_return_if_fail (mutex);
273
274   /* The runtime_mutex is the first (or only) member of GStaticMutex,
275    * see both versions (of glibconfig.h) in configure.in. Note, that
276    * this variable is NULL, if g_thread_init() hasn't been called or
277    * if we're using the default thread implementation and it provides
278    * static mutexes. */
279   runtime_mutex = ((GMutex**)mutex);
280
281   if (*runtime_mutex)
282     g_mutex_free (*runtime_mutex);
283
284   *runtime_mutex = NULL;
285 }
286
287 void
288 g_static_rec_mutex_init (GStaticRecMutex *mutex)
289 {
290   static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
291
292   g_return_if_fail (mutex);
293
294   *mutex = init_mutex;
295 }
296
297 void
298 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
299 {
300   GSystemThread self;
301
302   g_return_if_fail (mutex);
303
304   if (!g_thread_supported ())
305     return;
306
307   G_THREAD_UF (thread_self, (&self));
308
309   if (g_system_thread_equal (self, mutex->owner))
310     {
311       mutex->depth++;
312       return;
313     }
314   g_static_mutex_lock (&mutex->mutex);
315   g_system_thread_assign (mutex->owner, self);
316   mutex->depth = 1;
317 }
318
319 gboolean
320 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
321 {
322   GSystemThread self;
323
324   g_return_val_if_fail (mutex, FALSE);
325
326   if (!g_thread_supported ())
327     return TRUE;
328
329   G_THREAD_UF (thread_self, (&self));
330
331   if (g_system_thread_equal (self, mutex->owner))
332     {
333       mutex->depth++;
334       return TRUE;
335     }
336
337   if (!g_static_mutex_trylock (&mutex->mutex))
338     return FALSE;
339
340   g_system_thread_assign (mutex->owner, self);
341   mutex->depth = 1;
342   return TRUE;
343 }
344
345 void
346 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
347 {
348   g_return_if_fail (mutex);
349
350   if (!g_thread_supported ())
351     return;
352
353   if (mutex->depth > 1)
354     {
355       mutex->depth--;
356       return;
357     }
358   g_system_thread_assign (mutex->owner, zero_thread);
359   g_static_mutex_unlock (&mutex->mutex);
360 }
361
362 void
363 g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
364                                 guint            depth)
365 {
366   GSystemThread self;
367   g_return_if_fail (mutex);
368
369   if (!g_thread_supported ())
370     return;
371
372   if (depth == 0)
373     return;
374
375   G_THREAD_UF (thread_self, (&self));
376
377   if (g_system_thread_equal (self, mutex->owner))
378     {
379       mutex->depth += depth;
380       return;
381     }
382   g_static_mutex_lock (&mutex->mutex);
383   g_system_thread_assign (mutex->owner, self);
384   mutex->depth = depth;
385 }
386
387 guint
388 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
389 {
390   guint depth;
391
392   g_return_val_if_fail (mutex, 0);
393
394   if (!g_thread_supported ())
395     return 1;
396
397   depth = mutex->depth;
398
399   g_system_thread_assign (mutex->owner, zero_thread);
400   mutex->depth = 0;
401   g_static_mutex_unlock (&mutex->mutex);
402
403   return depth;
404 }
405
406 void
407 g_static_rec_mutex_free (GStaticRecMutex *mutex)
408 {
409   g_return_if_fail (mutex);
410
411   g_static_mutex_free (&mutex->mutex);
412 }
413
414 void
415 g_static_private_init (GStaticPrivate *private_key)
416 {
417   private_key->index = 0;
418 }
419
420 gpointer
421 g_static_private_get (GStaticPrivate *private_key)
422 {
423   GRealThread *self = (GRealThread*) g_thread_self ();
424   GArray *array;
425
426   array = self->private_data;
427   if (!array)
428     return NULL;
429
430   if (!private_key->index)
431     return NULL;
432   else if (private_key->index <= array->len)
433     return g_array_index (array, GStaticPrivateNode,
434                           private_key->index - 1).data;
435   else
436     return NULL;
437 }
438
439 void
440 g_static_private_set (GStaticPrivate *private_key,
441                       gpointer        data,
442                       GDestroyNotify  notify)
443 {
444   GRealThread *self = (GRealThread*) g_thread_self ();
445   GArray *array;
446   static guint next_index = 0;
447   GStaticPrivateNode *node;
448
449   array = self->private_data;
450   if (!array)
451     {
452       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
453       self->private_data = array;
454     }
455
456   if (!private_key->index)
457     {
458       G_LOCK (g_thread);
459
460       if (!private_key->index)
461         {
462           if (g_thread_free_indeces)
463             {
464               private_key->index =
465                 GPOINTER_TO_UINT (g_thread_free_indeces->data);
466               g_thread_free_indeces =
467                 g_slist_delete_link (g_thread_free_indeces,
468                                      g_thread_free_indeces);
469             }
470           else
471             private_key->index = ++next_index;
472         }
473
474       G_UNLOCK (g_thread);
475     }
476
477   if (private_key->index > array->len)
478     g_array_set_size (array, private_key->index);
479
480   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
481   if (node->destroy)
482     {
483       gpointer ddata = node->data;
484       GDestroyNotify ddestroy = node->destroy;
485
486       node->data = data;
487       node->destroy = notify;
488
489       ddestroy (ddata);
490     }
491   else
492     {
493       node->data = data;
494       node->destroy = notify;
495     }
496 }
497
498 void
499 g_static_private_free (GStaticPrivate *private_key)
500 {
501   guint idx = private_key->index;
502   GRealThread *thread;
503
504   if (!idx)
505     return;
506
507   private_key->index = 0;
508
509   G_LOCK (g_thread);
510
511   thread = g_thread_all_threads;
512   while (thread)
513     {
514       GArray *array = thread->private_data;
515       thread = thread->next;
516
517       if (array && idx <= array->len)
518         {
519           GStaticPrivateNode *node = &g_array_index (array,
520                                                      GStaticPrivateNode,
521                                                      idx - 1);
522           gpointer ddata = node->data;
523           GDestroyNotify ddestroy = node->destroy;
524
525           node->data = NULL;
526           node->destroy = NULL;
527
528           if (ddestroy)
529             {
530               G_UNLOCK (g_thread);
531               ddestroy (ddata);
532               G_LOCK (g_thread);
533             }
534         }
535     }
536   g_thread_free_indeces = g_slist_prepend (g_thread_free_indeces,
537                                            GUINT_TO_POINTER (idx));
538   G_UNLOCK (g_thread);
539 }
540
541 static void
542 g_thread_cleanup (gpointer data)
543 {
544   if (data)
545     {
546       GRealThread* thread = data;
547       if (thread->private_data)
548         {
549           GArray* array = thread->private_data;
550           guint i;
551
552           for (i = 0; i < array->len; i++ )
553             {
554               GStaticPrivateNode *node =
555                 &g_array_index (array, GStaticPrivateNode, i);
556               if (node->destroy)
557                 node->destroy (node->data);
558             }
559           g_array_free (array, TRUE);
560         }
561
562       /* We only free the thread structure, if it isn't joinable. If
563          it is, the structure is freed in g_thread_join */
564       if (!thread->thread.joinable)
565         {
566           GRealThread *t, *p;
567
568           G_LOCK (g_thread);
569           for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
570             {
571               if (t == thread)
572                 {
573                   if (p)
574                     p->next = t->next;
575                   else
576                     g_thread_all_threads = t->next;
577                   break;
578                 }
579             }
580           G_UNLOCK (g_thread);
581
582           /* Just to make sure, this isn't used any more */
583           g_system_thread_assign (thread->system_thread, zero_thread);
584           g_free (thread);
585         }
586     }
587 }
588
589 static void
590 g_thread_fail (void)
591 {
592   g_error ("The thread system is not yet initialized.");
593 }
594
595 #define G_NSEC_PER_SEC 1000000000
596
597 static guint64
598 gettime (void)
599 {
600 #ifdef G_OS_WIN32
601   guint64 v;
602
603   /* Returns 100s of nanoseconds since start of 1601 */
604   GetSystemTimeAsFileTime ((FILETIME *)&v);
605
606   /* Offset to Unix epoch */
607   v -= G_GINT64_CONSTANT (116444736000000000);
608   /* Convert to nanoseconds */
609   v *= 100;
610
611   return v;
612 #else
613   struct timeval tv;
614
615   gettimeofday (&tv, NULL);
616
617   return (guint64) tv.tv_sec * G_NSEC_PER_SEC + tv.tv_usec * (G_NSEC_PER_SEC / G_USEC_PER_SEC); 
618 #endif
619 }
620
621 static gpointer
622 g_thread_create_proxy (gpointer data)
623 {
624   GRealThread* thread = data;
625
626   g_assert (data);
627
628   /* This has to happen before G_LOCK, as that might call g_thread_self */
629   g_private_set (g_thread_specific_private, data);
630
631   /* the lock makes sure, that thread->system_thread is written,
632      before thread->thread.func is called. See g_thread_create. */
633   G_LOCK (g_thread);
634   G_UNLOCK (g_thread);
635
636   thread->retval = thread->thread.func (thread->thread.data);
637
638   return NULL;
639 }
640
641 GThread*
642 g_thread_create_full (GThreadFunc       func,
643                       gpointer          data,
644                       gulong            stack_size,
645                       gboolean          joinable,
646                       gboolean          bound,
647                       GThreadPriority   priority,
648                       GError          **error)
649 {
650   GRealThread* result;
651   GError *local_error = NULL;
652   g_return_val_if_fail (func, NULL);
653   g_return_val_if_fail (priority >= G_THREAD_PRIORITY_LOW, NULL);
654   g_return_val_if_fail (priority <= G_THREAD_PRIORITY_URGENT, NULL);
655
656   result = g_new0 (GRealThread, 1);
657
658   result->thread.joinable = joinable;
659   result->thread.priority = priority;
660   result->thread.func = func;
661   result->thread.data = data;
662   result->private_data = NULL;
663   G_LOCK (g_thread);
664   G_THREAD_UF (thread_create, (g_thread_create_proxy, result,
665                                stack_size, joinable, bound, priority,
666                                &result->system_thread, &local_error));
667   if (!local_error)
668     {
669       result->next = g_thread_all_threads;
670       g_thread_all_threads = result;
671     }
672   G_UNLOCK (g_thread);
673
674   if (local_error)
675     {
676       g_propagate_error (error, local_error);
677       g_free (result);
678       return NULL;
679     }
680
681   return (GThread*) result;
682 }
683
684 void
685 g_thread_exit (gpointer retval)
686 {
687   GRealThread* real = (GRealThread*) g_thread_self ();
688   real->retval = retval;
689   G_THREAD_CF (thread_exit, (void)0, ());
690 }
691
692 gpointer
693 g_thread_join (GThread* thread)
694 {
695   GRealThread* real = (GRealThread*) thread;
696   GRealThread *p, *t;
697   gpointer retval;
698
699   g_return_val_if_fail (thread, NULL);
700   g_return_val_if_fail (thread->joinable, NULL);
701   g_return_val_if_fail (!g_system_thread_equal (real->system_thread,
702                                                 zero_thread), NULL);
703
704   G_THREAD_UF (thread_join, (&real->system_thread));
705
706   retval = real->retval;
707
708   G_LOCK (g_thread);
709   for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
710     {
711       if (t == (GRealThread*) thread)
712         {
713           if (p)
714             p->next = t->next;
715           else
716             g_thread_all_threads = t->next;
717           break;
718         }
719     }
720   G_UNLOCK (g_thread);
721
722   /* Just to make sure, this isn't used any more */
723   thread->joinable = 0;
724   g_system_thread_assign (real->system_thread, zero_thread);
725
726   /* the thread structure for non-joinable threads is freed upon
727      thread end. We free the memory here. This will leave a loose end,
728      if a joinable thread is not joined. */
729
730   g_free (thread);
731
732   return retval;
733 }
734
735 void
736 g_thread_set_priority (GThread* thread,
737                        GThreadPriority priority)
738 {
739   GRealThread* real = (GRealThread*) thread;
740
741   g_return_if_fail (thread);
742   g_return_if_fail (!g_system_thread_equal (real->system_thread, zero_thread));
743   g_return_if_fail (priority >= G_THREAD_PRIORITY_LOW);
744   g_return_if_fail (priority <= G_THREAD_PRIORITY_URGENT);
745
746   thread->priority = priority;
747
748   G_THREAD_CF (thread_set_priority, (void)0,
749                (&real->system_thread, priority));
750 }
751
752 GThread*
753 g_thread_self (void)
754 {
755   GRealThread* thread = g_private_get (g_thread_specific_private);
756
757   if (!thread)
758     {
759       /* If no thread data is available, provide and set one.  This
760          can happen for the main thread and for threads, that are not
761          created by GLib. */
762       thread = g_new0 (GRealThread, 1);
763       thread->thread.joinable = FALSE; /* This is a save guess */
764       thread->thread.priority = G_THREAD_PRIORITY_NORMAL; /* This is
765                                                              just a guess */
766       thread->thread.func = NULL;
767       thread->thread.data = NULL;
768       thread->private_data = NULL;
769
770       if (g_thread_supported ())
771         G_THREAD_UF (thread_self, (&thread->system_thread));
772
773       g_private_set (g_thread_specific_private, thread);
774
775       G_LOCK (g_thread);
776       thread->next = g_thread_all_threads;
777       g_thread_all_threads = thread;
778       G_UNLOCK (g_thread);
779     }
780
781   return (GThread*)thread;
782 }
783
784 void
785 g_static_rw_lock_init (GStaticRWLock* lock)
786 {
787   static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
788
789   g_return_if_fail (lock);
790
791   *lock = init_lock;
792 }
793
794 inline static void
795 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
796 {
797   if (!*cond)
798       *cond = g_cond_new ();
799   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
800 }
801
802 inline static void
803 g_static_rw_lock_signal (GStaticRWLock* lock)
804 {
805   if (lock->want_to_write && lock->write_cond)
806     g_cond_signal (lock->write_cond);
807   else if (lock->want_to_read && lock->read_cond)
808     g_cond_broadcast (lock->read_cond);
809 }
810
811 void
812 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
813 {
814   g_return_if_fail (lock);
815
816   if (!g_threads_got_initialized)
817     return;
818
819   g_static_mutex_lock (&lock->mutex);
820   lock->want_to_read++;
821   while (lock->have_writer || lock->want_to_write)
822     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
823   lock->want_to_read--;
824   lock->read_counter++;
825   g_static_mutex_unlock (&lock->mutex);
826 }
827
828 gboolean
829 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
830 {
831   gboolean ret_val = FALSE;
832
833   g_return_val_if_fail (lock, FALSE);
834
835   if (!g_threads_got_initialized)
836     return TRUE;
837
838   g_static_mutex_lock (&lock->mutex);
839   if (!lock->have_writer && !lock->want_to_write)
840     {
841       lock->read_counter++;
842       ret_val = TRUE;
843     }
844   g_static_mutex_unlock (&lock->mutex);
845   return ret_val;
846 }
847
848 void
849 g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
850 {
851   g_return_if_fail (lock);
852
853   if (!g_threads_got_initialized)
854     return;
855
856   g_static_mutex_lock (&lock->mutex);
857   lock->read_counter--;
858   if (lock->read_counter == 0)
859     g_static_rw_lock_signal (lock);
860   g_static_mutex_unlock (&lock->mutex);
861 }
862
863 void
864 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
865 {
866   g_return_if_fail (lock);
867
868   if (!g_threads_got_initialized)
869     return;
870
871   g_static_mutex_lock (&lock->mutex);
872   lock->want_to_write++;
873   while (lock->have_writer || lock->read_counter)
874     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
875   lock->want_to_write--;
876   lock->have_writer = TRUE;
877   g_static_mutex_unlock (&lock->mutex);
878 }
879
880 gboolean
881 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
882 {
883   gboolean ret_val = FALSE;
884
885   g_return_val_if_fail (lock, FALSE);
886
887   if (!g_threads_got_initialized)
888     return TRUE;
889
890   g_static_mutex_lock (&lock->mutex);
891   if (!lock->have_writer && !lock->read_counter)
892     {
893       lock->have_writer = TRUE;
894       ret_val = TRUE;
895     }
896   g_static_mutex_unlock (&lock->mutex);
897   return ret_val;
898 }
899
900 void
901 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
902 {
903   g_return_if_fail (lock);
904
905   if (!g_threads_got_initialized)
906     return;
907
908   g_static_mutex_lock (&lock->mutex);
909   lock->have_writer = FALSE;
910   g_static_rw_lock_signal (lock);
911   g_static_mutex_unlock (&lock->mutex);
912 }
913
914 void
915 g_static_rw_lock_free (GStaticRWLock* lock)
916 {
917   g_return_if_fail (lock);
918
919   if (lock->read_cond)
920     {
921       g_cond_free (lock->read_cond);
922       lock->read_cond = NULL;
923     }
924   if (lock->write_cond)
925     {
926       g_cond_free (lock->write_cond);
927       lock->write_cond = NULL;
928     }
929   g_static_mutex_free (&lock->mutex);
930 }
931
932 /**
933  * g_thread_foreach
934  * @thread_func: function to call for all GThread structures
935  * @user_data:   second argument to @thread_func
936  *
937  * Call @thread_func on all existing #GThread structures. Note that
938  * threads may decide to exit while @thread_func is running, so
939  * without intimate knowledge about the lifetime of foreign threads,
940  * @thread_func shouldn't access the GThread* pointer passed in as
941  * first argument. However, @thread_func will not be called for threads
942  * which are known to have exited already.
943  *
944  * Due to thread lifetime checks, this function has an execution complexity
945  * which is quadratic in the number of existing threads.
946  *
947  * Since: 2.10
948  */
949 void
950 g_thread_foreach (GFunc    thread_func,
951                   gpointer user_data)
952 {
953   GSList *slist = NULL;
954   GRealThread *thread;
955   g_return_if_fail (thread_func != NULL);
956   /* snapshot the list of threads for iteration */
957   G_LOCK (g_thread);
958   for (thread = g_thread_all_threads; thread; thread = thread->next)
959     slist = g_slist_prepend (slist, thread);
960   G_UNLOCK (g_thread);
961   /* walk the list, skipping non-existant threads */
962   while (slist)
963     {
964       GSList *node = slist;
965       slist = node->next;
966       /* check whether the current thread still exists */
967       G_LOCK (g_thread);
968       for (thread = g_thread_all_threads; thread; thread = thread->next)
969         if (thread == node->data)
970           break;
971       G_UNLOCK (g_thread);
972       if (thread)
973         thread_func (thread, user_data);
974       g_slist_free_1 (node);
975     }
976 }
977
978 /**
979  * g_thread_get_initialized
980  *
981  * Indicates if g_thread_init() has been called.
982  *
983  * Returns: %TRUE if threads have been initialized.
984  *
985  * Since: 2.20
986  */
987 gboolean
988 g_thread_get_initialized ()
989 {
990   return g_thread_supported ();
991 }
992
993 #define __G_THREAD_C__
994 #include "galiasdef.c"