Move GThread docs around
[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 /* Prelude {{{1 ----------------------------------------------------------- */
25
26 /*
27  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
28  * file for a list of people on the GLib Team.  See the ChangeLog
29  * files for a list of changes.  These files are distributed with
30  * GLib at ftp://ftp.gtk.org/pub/gtk/.
31  */
32
33 /*
34  * MT safe
35  */
36
37 /* implement gthread.h's inline functions */
38 #define G_IMPLEMENT_INLINES 1
39 #define __G_THREAD_C__
40
41 #include "config.h"
42
43 #include "deprecated/gthread.h"
44 #include "gthreadprivate.h"
45 #include "gslice.h"
46 #include "gmain.h"
47
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51
52 #ifndef G_OS_WIN32
53 #include <sys/time.h>
54 #include <time.h>
55 #else
56 #include <windows.h>
57 #endif /* G_OS_WIN32 */
58
59 #include <string.h>
60
61 #include "garray.h"
62 #include "gbitlock.h"
63 #include "gslist.h"
64 #include "gtestutils.h"
65 #include "gtimer.h"
66
67 /**
68  * SECTION:threads
69  * @title: Threads
70  * @short_description: portable support for threads, mutexes, locks,
71  *     conditions and thread private data
72  * @see_also: #GThreadPool, #GAsyncQueue
73  *
74  * Threads act almost like processes, but unlike processes all threads
75  * of one process share the same memory. This is good, as it provides
76  * easy communication between the involved threads via this shared
77  * memory, and it is bad, because strange things (so called
78  * "Heisenbugs") might happen if the program is not carefully designed.
79  * In particular, due to the concurrent nature of threads, no
80  * assumptions on the order of execution of code running in different
81  * threads can be made, unless order is explicitly forced by the
82  * programmer through synchronization primitives.
83  *
84  * The aim of the thread-related functions in GLib is to provide a
85  * portable means for writing multi-threaded software. There are
86  * primitives for mutexes to protect the access to portions of memory
87  * (#GMutex, #GRecMutex and #GRWLock). There is a facility to use
88  * individual bits for locks (g_bit_lock()). There are primitives
89  * for condition variables to allow synchronization of threads (#GCond).
90  * There are primitives for thread-private data - data that every thread
91  * has a private instance of (#GPrivate, #GStaticPrivate). There are
92  * facilities for one-time initialization (#GOnce, g_once_init_enter()).
93  * Finally there are primitives to create and manage threads (#GThread).
94  *
95  * The threading system is initialized with g_thread_init(), which
96  * takes an optional custom thread implementation or %NULL for the
97  * default implementation. If you want to call g_thread_init() with a
98  * non-%NULL argument this must be done before executing any other GLib
99  * functions (except g_mem_set_vtable()). This is a requirement even if
100  * no threads are in fact ever created by the process.
101  *
102  * Calling g_thread_init() with a %NULL argument is somewhat more
103  * relaxed. You may call any other glib functions in the main thread
104  * before g_thread_init() as long as g_thread_init() is not called from
105  * a glib callback, or with any locks held. However, many libraries
106  * above glib does not support late initialization of threads, so doing
107  * this should be avoided if possible.
108  *
109  * Please note that since version 2.24 the GObject initialization
110  * function g_type_init() initializes threads (with a %NULL argument),
111  * so most applications, including those using GTK+ will run with
112  * threads enabled. If you want a special thread implementation, make
113  * sure you call g_thread_init() before g_type_init() is called.
114  *
115  * After calling g_thread_init(), GLib is completely thread safe (all
116  * global data is automatically locked), but individual data structure
117  * instances are not automatically locked for performance reasons. So,
118  * for example you must coordinate accesses to the same #GHashTable
119  * from multiple threads. The two notable exceptions from this rule
120  * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
121  * threadsafe and need no further application-level locking to be
122  * accessed from multiple threads.
123  */
124
125 /**
126  * G_THREADS_IMPL_POSIX:
127  *
128  * This macro is defined if POSIX style threads are used.
129  */
130
131 /**
132  * G_THREADS_IMPL_WIN32:
133  *
134  * This macro is defined if Windows style threads are used.
135  */
136
137 /**
138  * G_THREADS_ENABLED:
139  *
140  * This macro is defined, for backward compatibility, to indicate that
141  * GLib has been compiled with thread support. As of GLib 2.28, it is
142  * always defined.
143  **/
144
145 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
146
147 /* IMPLEMENTATION NOTE:
148  *
149  * G_LOCK_DEFINE and friends are convenience macros defined in
150  * gthread.h.  Their documentation lives here.
151  */
152
153 /**
154  * G_LOCK_DEFINE:
155  * @name: the name of the lock.
156  *
157  * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
158  * with the advantage that they will expand to nothing in programs
159  * compiled against a thread-disabled GLib, saving code and memory
160  * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
161  * variable definitions may appear in programs, i.e. in the first block
162  * of a function or outside of functions. The @name parameter will be
163  * mangled to get the name of the #GStaticMutex. This means that you
164  * can use names of existing variables as the parameter - e.g. the name
165  * of the variable you intent to protect with the lock. Look at our
166  * <function>give_me_next_number()</function> example using the
167  * %G_LOCK_* macros:
168  *
169  * <example>
170  *  <title>Using the %G_LOCK_* convenience macros</title>
171  *  <programlisting>
172  *   G_LOCK_DEFINE (current_number);
173  *
174  *   int
175  *   give_me_next_number (void)
176  *   {
177  *     static int current_number = 0;
178  *     int ret_val;
179  *
180  *     G_LOCK (current_number);
181  *     ret_val = current_number = calc_next_number (current_number);
182  *     G_UNLOCK (current_number);
183  *
184  *     return ret_val;
185  *   }
186  *  </programlisting>
187  * </example>
188  **/
189
190 /**
191  * G_LOCK_DEFINE_STATIC:
192  * @name: the name of the lock.
193  *
194  * This works like #G_LOCK_DEFINE, but it creates a static object.
195  **/
196
197 /**
198  * G_LOCK_EXTERN:
199  * @name: the name of the lock.
200  *
201  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
202  * module.
203  **/
204
205 /**
206  * G_LOCK:
207  * @name: the name of the lock.
208  *
209  * Works like g_mutex_lock(), but for a lock defined with
210  * #G_LOCK_DEFINE.
211  **/
212
213 /**
214  * G_TRYLOCK:
215  * @name: the name of the lock.
216  * @Returns: %TRUE, if the lock could be locked.
217  *
218  * Works like g_mutex_trylock(), but for a lock defined with
219  * #G_LOCK_DEFINE.
220  **/
221
222 /**
223  * G_UNLOCK:
224  * @name: the name of the lock.
225  *
226  * Works like g_mutex_unlock(), but for a lock defined with
227  * #G_LOCK_DEFINE.
228  **/
229
230
231 /* GMutex Documentation {{{1 ------------------------------------------ */
232
233 /**
234  * GMutex:
235  *
236  * The #GMutex struct is an opaque data structure to represent a mutex
237  * (mutual exclusion). It can be used to protect data against shared
238  * access. Take for example the following function:
239  *
240  * <example>
241  *  <title>A function which will not work in a threaded environment</title>
242  *  <programlisting>
243  *   int
244  *   give_me_next_number (void)
245  *   {
246  *     static int current_number = 0;
247  *
248  *     /<!-- -->* now do a very complicated calculation to calculate the new
249  *      * number, this might for example be a random number generator
250  *      *<!-- -->/
251  *     current_number = calc_next_number (current_number);
252  *
253  *     return current_number;
254  *   }
255  *  </programlisting>
256  * </example>
257  *
258  * It is easy to see that this won't work in a multi-threaded
259  * application. There current_number must be protected against shared
260  * access. A first naive implementation would be:
261  *
262  * <example>
263  *  <title>The wrong way to write a thread-safe function</title>
264  *  <programlisting>
265  *   int
266  *   give_me_next_number (void)
267  *   {
268  *     static int current_number = 0;
269  *     int ret_val;
270  *     static GMutex * mutex = NULL;
271  *
272  *     if (!mutex) mutex = g_mutex_new (<!-- -->);
273  *
274  *     g_mutex_lock (mutex);
275  *     ret_val = current_number = calc_next_number (current_number);
276  *     g_mutex_unlock (mutex);
277  *
278  *     return ret_val;
279  *   }
280  *  </programlisting>
281  * </example>
282  *
283  * This looks like it would work, but there is a race condition while
284  * constructing the mutex and this code cannot work reliable. Please do
285  * not use such constructs in your own programs! One working solution
286  * is:
287  *
288  * <example>
289  *  <title>A correct thread-safe function</title>
290  *  <programlisting>
291  *   static GMutex *give_me_next_number_mutex = NULL;
292  *
293  *   /<!-- -->* this function must be called before any call to
294  *    * give_me_next_number(<!-- -->)
295  *    *
296  *    * it must be called exactly once.
297  *    *<!-- -->/
298  *   void
299  *   init_give_me_next_number (void)
300  *   {
301  *     g_assert (give_me_next_number_mutex == NULL);
302  *     give_me_next_number_mutex = g_mutex_new (<!-- -->);
303  *   }
304  *
305  *   int
306  *   give_me_next_number (void)
307  *   {
308  *     static int current_number = 0;
309  *     int ret_val;
310  *
311  *     g_mutex_lock (give_me_next_number_mutex);
312  *     ret_val = current_number = calc_next_number (current_number);
313  *     g_mutex_unlock (give_me_next_number_mutex);
314  *
315  *     return ret_val;
316  *   }
317  *  </programlisting>
318  * </example>
319  *
320  * A statically initialized #GMutex provides an even simpler and safer
321  * way of doing this:
322  *
323  * <example>
324  *  <title>Using a statically allocated mutex</title>
325  *  <programlisting>
326  *   int
327  *   give_me_next_number (void)
328  *   {
329  *     static GMutex mutex = G_MUTEX_INIT;
330  *     static int current_number = 0;
331  *     int ret_val;
332  *
333  *     g_mutex_lock (&amp;mutex);
334  *     ret_val = current_number = calc_next_number (current_number);
335  *     g_mutex_unlock (&amp;mutex);
336  *
337  *     return ret_val;
338  *   }
339  *  </programlisting>
340  * </example>
341  *
342  * A #GMutex should only be accessed via <function>g_mutex_</function>
343  * functions.
344  */
345
346 /**
347  * G_MUTEX_INIT:
348  *
349  * Initializer for statically allocated #GMutexes.
350  * Alternatively, g_mutex_init() can be used.
351  *
352  * |[
353  *   GMutex mutex = G_MUTEX_INIT;
354  * ]|
355  *
356  * Since: 2.32
357  */
358
359 /* GRecMutex Documentation {{{1 -------------------------------------- */
360
361 /**
362  * GRecMutex:
363  *
364  * The GRecMutex struct is an opaque data structure to represent a
365  * recursive mutex. It is similar to a #GMutex with the difference
366  * that it is possible to lock a GRecMutex multiple times in the same
367  * thread without deadlock. When doing so, care has to be taken to
368  * unlock the recursive mutex as often as it has been locked.
369  *
370  * A GRecMutex should only be accessed with the
371  * <function>g_rec_mutex_</function> functions. Before a GRecMutex
372  * can be used, it has to be initialized with #G_REC_MUTEX_INIT or
373  * g_rec_mutex_init().
374  *
375  * Since: 2.32
376  */
377
378 /**
379  * G_REC_MUTEX_INIT:
380  *
381  * Initializer for statically allocated #GRecMutexes.
382  * Alternatively, g_rec_mutex_init() can be used.
383  *
384  * |[
385  *   GRecMutex mutex = G_REC_MUTEX_INIT;
386  * ]|
387  *
388  * Since: 2.32
389  */
390
391 /* GRWLock Documentation {{{1 ---------------------------------------- */
392
393 /**
394  * GRWLock:
395  *
396  * The GRWLock struct is an opaque data structure to represent a
397  * reader-writer lock. It is similar to a #GMutex in that it allows
398  * multiple threads to coordinate access to a shared resource.
399  *
400  * The difference to a mutex is that a reader-writer lock discriminates
401  * between read-only ('reader') and full ('writer') access. While only
402  * one thread at a time is allowed write access (by holding the 'writer'
403  * lock via g_rw_lock_writer_lock()), multiple threads can gain
404  * simultaneous read-only access (by holding the 'reader' lock via
405  * g_rw_lock_reader_lock()).
406  *
407  * <example>
408  *  <title>An array with access functions</title>
409  *  <programlisting>
410  *   GRWLock lock = G_RW_LOCK_INIT;
411  *   GPtrArray *array;
412  *
413  *   gpointer
414  *   my_array_get (guint index)
415  *   {
416  *     gpointer retval = NULL;
417  *
418  *     if (!array)
419  *       return NULL;
420  *
421  *     g_rw_lock_reader_lock (&amp;lock);
422  *     if (index &lt; array->len)
423  *       retval = g_ptr_array_index (array, index);
424  *     g_rw_lock_reader_unlock (&amp;lock);
425  *
426  *     return retval;
427  *   }
428  *
429  *   void
430  *   my_array_set (guint index, gpointer data)
431  *   {
432  *     g_rw_lock_writer_lock (&amp;lock);
433  *
434  *     if (!array)
435  *       array = g_ptr_array_new (<!-- -->);
436  *
437  *     if (index >= array->len)
438  *       g_ptr_array_set_size (array, index+1);
439  *     g_ptr_array_index (array, index) = data;
440  *
441  *     g_rw_lock_writer_unlock (&amp;lock);
442  *   }
443  *  </programlisting>
444  *  <para>
445  *    This example shows an array which can be accessed by many readers
446  *    (the <function>my_array_get()</function> function) simultaneously,
447  *    whereas the writers (the <function>my_array_set()</function>
448  *    function) will only be allowed once at a time and only if no readers
449  *    currently access the array. This is because of the potentially
450  *    dangerous resizing of the array. Using these functions is fully
451  *    multi-thread safe now.
452  *  </para>
453  * </example>
454  *
455  * A GRWLock should only be accessed with the
456  * <function>g_rw_lock_</function> functions. Before it can be used,
457  * it has to be initialized with #G_RW_LOCK_INIT or g_rw_lock_init().
458  *
459  * Since: 2.32
460  */
461
462 /**
463  * G_RW_LOCK_INIT:
464  *
465  * Initializer for statically allocated #GRWLocks.
466  * Alternatively, g_rw_lock_init_init() can be used.
467  *
468  * |[
469  *   GRWLock lock = G_RW_LOCK_INIT;
470  * ]|
471  *
472  * Since: 2.32
473  */
474
475 /* GCond Documentation {{{1 ------------------------------------------ */
476
477 /**
478  * GCond:
479  *
480  * The #GCond struct is an opaque data structure that represents a
481  * condition. Threads can block on a #GCond if they find a certain
482  * condition to be false. If other threads change the state of this
483  * condition they signal the #GCond, and that causes the waiting
484  * threads to be woken up.
485  *
486  * <example>
487  *  <title>
488  *   Using GCond to block a thread until a condition is satisfied
489  *  </title>
490  *  <programlisting>
491  *   GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
492  *   GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
493  *   gpointer current_data = NULL;
494  *
495  *   void
496  *   push_data (gpointer data)
497  *   {
498  *     g_mutex_lock (data_mutex);
499  *     current_data = data;
500  *     g_cond_signal (data_cond);
501  *     g_mutex_unlock (data_mutex);
502  *   }
503  *
504  *   gpointer
505  *   pop_data (void)
506  *   {
507  *     gpointer data;
508  *
509  *     g_mutex_lock (data_mutex);
510  *     while (!current_data)
511  *       g_cond_wait (data_cond, data_mutex);
512  *     data = current_data;
513  *     current_data = NULL;
514  *     g_mutex_unlock (data_mutex);
515  *
516  *     return data;
517  *   }
518  *  </programlisting>
519  * </example>
520  *
521  * Whenever a thread calls pop_data() now, it will wait until
522  * current_data is non-%NULL, i.e. until some other thread
523  * has called push_data().
524  *
525  * <note><para>It is important to use the g_cond_wait() and
526  * g_cond_timed_wait() functions only inside a loop which checks for the
527  * condition to be true.  It is not guaranteed that the waiting thread
528  * will find the condition fulfilled after it wakes up, even if the
529  * signaling thread left the condition in that state: another thread may
530  * have altered the condition before the waiting thread got the chance
531  * to be woken up, even if the condition itself is protected by a
532  * #GMutex, like above.</para></note>
533  *
534  * A #GCond should only be accessed via the <function>g_cond_</function>
535  * functions.
536  */
537
538 /**
539  * G_COND_INIT:
540  *
541  * Initializer for statically allocated #GConds.
542  * Alternatively, g_cond_init() can be used.
543  *
544  * |[
545  *   GCond cond = G_COND_INIT;
546  * ]|
547  *
548  * Since: 2.32
549  */
550
551 /* GPrivate Documentation {{{1 --------------------------------------- */
552
553 /**
554  * GPrivate:
555  *
556  * <note><para>
557  * #GStaticPrivate is a better choice for most uses.
558  * </para></note>
559  *
560  * The #GPrivate struct is an opaque data structure to represent a
561  * thread private data key. Threads can thereby obtain and set a
562  * pointer which is private to the current thread. Take our
563  * <function>give_me_next_number(<!-- -->)</function> example from
564  * above.  Suppose we don't want <literal>current_number</literal> to be
565  * shared between the threads, but instead to be private to each thread.
566  * This can be done as follows:
567  *
568  * <example>
569  *  <title>Using GPrivate for per-thread data</title>
570  *  <programlisting>
571  *   GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
572  *                                           with g_private_new (g_free); *<!-- -->/
573  *
574  *   int
575  *   give_me_next_number (void)
576  *   {
577  *     int *current_number = g_private_get (current_number_key);
578  *
579  *     if (!current_number)
580  *       {
581  *         current_number = g_new (int, 1);
582  *         *current_number = 0;
583  *         g_private_set (current_number_key, current_number);
584  *       }
585  *
586  *     *current_number = calc_next_number (*current_number);
587  *
588  *     return *current_number;
589  *   }
590  *  </programlisting>
591  * </example>
592  *
593  * Here the pointer belonging to the key
594  * <literal>current_number_key</literal> is read. If it is %NULL, it has
595  * not been set yet. Then get memory for an integer value, assign this
596  * memory to the pointer and write the pointer back. Now we have an
597  * integer value that is private to the current thread.
598  *
599  * The #GPrivate struct should only be accessed via the
600  * <function>g_private_</function> functions.
601  */
602
603 /* GThread Documentation {{{1 ---------------------------------------- */
604 /**
605  * GThread:
606  *
607  * The #GThread struct represents a running thread. It has three public
608  * read-only members, but the underlying struct is bigger, so you must
609  * not copy this struct.
610  *
611  * <note><para>Resources for a joinable thread are not fully released
612  * until g_thread_join() is called for that thread.</para></note>
613  **/
614
615 /**
616  * GThreadFunc:
617  * @data: data passed to the thread.
618  * @Returns: the return value of the thread, which will be returned by
619  *           g_thread_join().
620  *
621  * Specifies the type of the @func functions passed to
622  * g_thread_create() or g_thread_create_full().
623  **/
624
625 /* GThreadError {{{1 ------------------------------------------------------- */
626 /**
627  * GThreadError:
628  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
629  *                        shortage. Try again later.
630  *
631  * Possible errors of thread related functions.
632  **/
633
634 /**
635  * G_THREAD_ERROR:
636  *
637  * The error domain of the GLib thread subsystem.
638  **/
639 GQuark
640 g_thread_error_quark (void)
641 {
642   return g_quark_from_static_string ("g_thread_error");
643 }
644
645 /* Miscellaneous Structures {{{1 ------------------------------------------ */
646
647 typedef struct _GRealThread GRealThread;
648 struct  _GRealThread
649 {
650   GThread thread;
651   /* Bit 0 protects private_data. To avoid deadlocks, do not block while
652    * holding this (particularly on the g_thread lock). */
653   volatile gint private_data_lock;
654   GArray *private_data;
655   GRealThread *next;
656   gpointer retval;
657   GSystemThread system_thread;
658 };
659
660 #define LOCK_PRIVATE_DATA(self)   g_bit_lock (&(self)->private_data_lock, 0)
661 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
662
663 static void    g_thread_cleanup (gpointer data);
664
665 /**
666  * g_thread_supported:
667  * @Returns: %TRUE, if the thread system is initialized.
668  *
669  * This function returns %TRUE if the thread system is initialized, and
670  * %FALSE if it is not.
671  *
672  * <note><para>This function is actually a macro. Apart from taking the
673  * address of it you can however use it as if it was a
674  * function.</para></note>
675  **/
676 /* Local Data {{{1 -------------------------------------------------------- */
677
678 gboolean         g_threads_got_initialized = FALSE;
679 GSystemThread    zero_thread; /* This is initialized to all zero */
680 GMutex           g_once_mutex = G_MUTEX_INIT;
681
682 static GCond     g_once_cond = G_COND_INIT;
683 static GPrivate  g_thread_specific_private;
684 static GRealThread *g_thread_all_threads = NULL;
685 static GSList   *g_thread_free_indices = NULL;
686 static GSList*   g_once_init_list = NULL;
687
688 G_LOCK_DEFINE_STATIC (g_thread);
689
690 /* Initialisation {{{1 ---------------------------------------------------- */
691
692 /**
693  * g_thread_init:
694  * @vtable: a function table of type #GThreadFunctions, that provides
695  *     the entry points to the thread system to be used. Since 2.32,
696  *     this parameter is ignored and should always be %NULL
697  *
698  * If you use GLib from more than one thread, you must initialize the
699  * thread system by calling g_thread_init().
700  *
701  * Since version 2.24, calling g_thread_init() multiple times is allowed,
702  * but nothing happens except for the first call.
703  *
704  * Since version 2.32, GLib does not support custom thread implementations
705  * anymore and the @vtable parameter is ignored and you should pass %NULL.
706  *
707  * <note><para>g_thread_init() must not be called directly or indirectly
708  * in a callback from GLib. Also no mutexes may be currently locked while
709  * calling g_thread_init().</para></note>
710  *
711  * <note><para>To use g_thread_init() in your program, you have to link
712  * with the libraries that the command <command>pkg-config --libs
713  * gthread-2.0</command> outputs. This is not the case for all the
714  * other thread-related functions of GLib. Those can be used without
715  * having to link with the thread libraries.</para></note>
716  */
717
718 void
719 g_thread_init_glib (void)
720 {
721   static gboolean already_done;
722   GRealThread* main_thread;
723
724   if (already_done)
725     return;
726
727   already_done = TRUE;
728
729   /* We let the main thread (the one that calls g_thread_init) inherit
730    * the static_private data set before calling g_thread_init
731    */
732   main_thread = (GRealThread*) g_thread_self ();
733
734   /* setup the basic threading system */
735   g_threads_got_initialized = TRUE;
736   g_private_init (&g_thread_specific_private, g_thread_cleanup);
737   g_private_set (&g_thread_specific_private, main_thread);
738   g_system_thread_self (&main_thread->system_thread);
739
740   /* accomplish log system initialization to enable messaging */
741   _g_messages_thread_init_nomessage ();
742 }
743
744 /* GOnce {{{1 ------------------------------------------------------------- */
745
746 /**
747  * GOnce:
748  * @status: the status of the #GOnce
749  * @retval: the value returned by the call to the function, if @status
750  *          is %G_ONCE_STATUS_READY
751  *
752  * A #GOnce struct controls a one-time initialization function. Any
753  * one-time initialization function must have its own unique #GOnce
754  * struct.
755  *
756  * Since: 2.4
757  **/
758
759 /**
760  * G_ONCE_INIT:
761  *
762  * A #GOnce must be initialized with this macro before it can be used.
763  *
764  * <informalexample>
765  *  <programlisting>
766  *   GOnce my_once = G_ONCE_INIT;
767  *  </programlisting>
768  * </informalexample>
769  *
770  * Since: 2.4
771  **/
772
773 /**
774  * GOnceStatus:
775  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
776  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
777  * @G_ONCE_STATUS_READY: the function has been called.
778  *
779  * The possible statuses of a one-time initialization function
780  * controlled by a #GOnce struct.
781  *
782  * Since: 2.4
783  **/
784
785 /**
786  * g_once:
787  * @once: a #GOnce structure
788  * @func: the #GThreadFunc function associated to @once. This function
789  *        is called only once, regardless of the number of times it and
790  *        its associated #GOnce struct are passed to g_once().
791  * @arg: data to be passed to @func
792  *
793  * The first call to this routine by a process with a given #GOnce
794  * struct calls @func with the given argument. Thereafter, subsequent
795  * calls to g_once()  with the same #GOnce struct do not call @func
796  * again, but return the stored result of the first call. On return
797  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
798  *
799  * For example, a mutex or a thread-specific data key must be created
800  * exactly once. In a threaded environment, calling g_once() ensures
801  * that the initialization is serialized across multiple threads.
802  *
803  * <note><para>Calling g_once() recursively on the same #GOnce struct in
804  * @func will lead to a deadlock.</para></note>
805  *
806  * <informalexample>
807  *  <programlisting>
808  *   gpointer
809  *   get_debug_flags (void)
810  *   {
811  *     static GOnce my_once = G_ONCE_INIT;
812  *
813  *     g_once (&my_once, parse_debug_flags, NULL);
814  *
815  *     return my_once.retval;
816  *   }
817  *  </programlisting>
818  * </informalexample>
819  *
820  * Since: 2.4
821  **/
822 gpointer
823 g_once_impl (GOnce       *once,
824              GThreadFunc  func,
825              gpointer     arg)
826 {
827   g_mutex_lock (&g_once_mutex);
828
829   while (once->status == G_ONCE_STATUS_PROGRESS)
830     g_cond_wait (&g_once_cond, &g_once_mutex);
831
832   if (once->status != G_ONCE_STATUS_READY)
833     {
834       once->status = G_ONCE_STATUS_PROGRESS;
835       g_mutex_unlock (&g_once_mutex);
836
837       once->retval = func (arg);
838
839       g_mutex_lock (&g_once_mutex);
840       once->status = G_ONCE_STATUS_READY;
841       g_cond_broadcast (&g_once_cond);
842     }
843
844   g_mutex_unlock (&g_once_mutex);
845
846   return once->retval;
847 }
848
849 /**
850  * g_once_init_enter:
851  * @value_location: location of a static initializable variable
852  *                  containing 0.
853  * @Returns: %TRUE if the initialization section should be entered,
854  *           %FALSE and blocks otherwise
855  *
856  * Function to be called when starting a critical initialization
857  * section. The argument @value_location must point to a static
858  * 0-initialized variable that will be set to a value other than 0 at
859  * the end of the initialization section. In combination with
860  * g_once_init_leave() and the unique address @value_location, it can
861  * be ensured that an initialization section will be executed only once
862  * during a program's life time, and that concurrent threads are
863  * blocked until initialization completed. To be used in constructs
864  * like this:
865  *
866  * <informalexample>
867  *  <programlisting>
868  *   static gsize initialization_value = 0;
869  *
870  *   if (g_once_init_enter (&amp;initialization_value))
871  *     {
872  *       gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
873  *
874  *       g_once_init_leave (&amp;initialization_value, setup_value);
875  *     }
876  *
877  *   /<!-- -->* use initialization_value here *<!-- -->/
878  *  </programlisting>
879  * </informalexample>
880  *
881  * Since: 2.14
882  **/
883 gboolean
884 g_once_init_enter_impl (volatile gsize *value_location)
885 {
886   gboolean need_init = FALSE;
887   g_mutex_lock (&g_once_mutex);
888   if (g_atomic_pointer_get (value_location) == NULL)
889     {
890       if (!g_slist_find (g_once_init_list, (void*) value_location))
891         {
892           need_init = TRUE;
893           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
894         }
895       else
896         do
897           g_cond_wait (&g_once_cond, &g_once_mutex);
898         while (g_slist_find (g_once_init_list, (void*) value_location));
899     }
900   g_mutex_unlock (&g_once_mutex);
901   return need_init;
902 }
903
904 /**
905  * g_once_init_leave:
906  * @value_location: location of a static initializable variable
907  *                  containing 0.
908  * @initialization_value: new non-0 value for *@value_location.
909  *
910  * Counterpart to g_once_init_enter(). Expects a location of a static
911  * 0-initialized initialization variable, and an initialization value
912  * other than 0. Sets the variable to the initialization value, and
913  * releases concurrent threads blocking in g_once_init_enter() on this
914  * initialization variable.
915  *
916  * Since: 2.14
917  **/
918 void
919 g_once_init_leave (volatile gsize *value_location,
920                    gsize           initialization_value)
921 {
922   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
923   g_return_if_fail (initialization_value != 0);
924   g_return_if_fail (g_once_init_list != NULL);
925
926   g_atomic_pointer_set (value_location, initialization_value);
927   g_mutex_lock (&g_once_mutex);
928   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
929   g_cond_broadcast (&g_once_cond);
930   g_mutex_unlock (&g_once_mutex);
931 }
932
933 /* GStaticPrivate {{{1 ---------------------------------------------------- */
934
935 typedef struct _GStaticPrivateNode GStaticPrivateNode;
936 struct _GStaticPrivateNode
937 {
938   gpointer       data;
939   GDestroyNotify destroy;
940 };
941
942 /**
943  * GStaticPrivate:
944  *
945  * A #GStaticPrivate works almost like a #GPrivate, but it has one
946  * significant advantage. It doesn't need to be created at run-time
947  * like a #GPrivate, but can be defined at compile-time. This is
948  * similar to the difference between #GMutex and #GStaticMutex. Now
949  * look at our <function>give_me_next_number()</function> example with
950  * #GStaticPrivate:
951  *
952  * <example>
953  *  <title>Using GStaticPrivate for per-thread data</title>
954  *  <programlisting>
955  *   int
956  *   give_me_next_number (<!-- -->)
957  *   {
958  *     static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
959  *     int *current_number = g_static_private_get (&amp;current_number_key);
960  *
961  *     if (!current_number)
962  *       {
963  *         current_number = g_new (int,1);
964  *         *current_number = 0;
965  *         g_static_private_set (&amp;current_number_key, current_number, g_free);
966  *       }
967  *
968  *     *current_number = calc_next_number (*current_number);
969  *
970  *     return *current_number;
971  *   }
972  *  </programlisting>
973  * </example>
974  **/
975
976 /**
977  * G_STATIC_PRIVATE_INIT:
978  *
979  * Every #GStaticPrivate must be initialized with this macro, before it
980  * can be used.
981  *
982  * |[
983  *   GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
984  * ]|
985  */
986
987 /**
988  * g_static_private_init:
989  * @private_key: a #GStaticPrivate to be initialized.
990  *
991  * Initializes @private_key. Alternatively you can initialize it with
992  * #G_STATIC_PRIVATE_INIT.
993  **/
994 void
995 g_static_private_init (GStaticPrivate *private_key)
996 {
997   private_key->index = 0;
998 }
999
1000 /**
1001  * g_static_private_get:
1002  * @private_key: a #GStaticPrivate.
1003  * @Returns: the corresponding pointer.
1004  *
1005  * Works like g_private_get() only for a #GStaticPrivate.
1006  *
1007  * This function works even if g_thread_init() has not yet been called.
1008  */
1009 gpointer
1010 g_static_private_get (GStaticPrivate *private_key)
1011 {
1012   GRealThread *self = (GRealThread*) g_thread_self ();
1013   GArray *array;
1014   gpointer ret = NULL;
1015
1016   LOCK_PRIVATE_DATA (self);
1017
1018   array = self->private_data;
1019
1020   if (array && private_key->index != 0 && private_key->index <= array->len)
1021     ret = g_array_index (array, GStaticPrivateNode,
1022                          private_key->index - 1).data;
1023
1024   UNLOCK_PRIVATE_DATA (self);
1025   return ret;
1026 }
1027
1028 /**
1029  * g_static_private_set:
1030  * @private_key: a #GStaticPrivate.
1031  * @data: the new pointer.
1032  * @notify: a function to be called with the pointer whenever the
1033  *          current thread ends or sets this pointer again.
1034  *
1035  * Sets the pointer keyed to @private_key for the current thread and
1036  * the function @notify to be called with that pointer (%NULL or
1037  * non-%NULL), whenever the pointer is set again or whenever the
1038  * current thread ends.
1039  *
1040  * This function works even if g_thread_init() has not yet been called.
1041  * If g_thread_init() is called later, the @data keyed to @private_key
1042  * will be inherited only by the main thread, i.e. the one that called
1043  * g_thread_init().
1044  *
1045  * <note><para>@notify is used quite differently from @destructor in
1046  * g_private_new().</para></note>
1047  */
1048 void
1049 g_static_private_set (GStaticPrivate *private_key,
1050                       gpointer        data,
1051                       GDestroyNotify  notify)
1052 {
1053   GRealThread *self = (GRealThread*) g_thread_self ();
1054   GArray *array;
1055   static guint next_index = 0;
1056   GStaticPrivateNode *node;
1057   gpointer ddata = NULL;
1058   GDestroyNotify ddestroy = NULL;
1059
1060   if (!private_key->index)
1061     {
1062       G_LOCK (g_thread);
1063
1064       if (!private_key->index)
1065         {
1066           if (g_thread_free_indices)
1067             {
1068               private_key->index =
1069                 GPOINTER_TO_UINT (g_thread_free_indices->data);
1070               g_thread_free_indices =
1071                 g_slist_delete_link (g_thread_free_indices,
1072                                      g_thread_free_indices);
1073             }
1074           else
1075             private_key->index = ++next_index;
1076         }
1077
1078       G_UNLOCK (g_thread);
1079     }
1080
1081   LOCK_PRIVATE_DATA (self);
1082
1083   array = self->private_data;
1084   if (!array)
1085     {
1086       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1087       self->private_data = array;
1088     }
1089
1090   if (private_key->index > array->len)
1091     g_array_set_size (array, private_key->index);
1092
1093   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1094
1095   ddata = node->data;
1096   ddestroy = node->destroy;
1097
1098   node->data = data;
1099   node->destroy = notify;
1100
1101   UNLOCK_PRIVATE_DATA (self);
1102
1103   if (ddestroy)
1104     ddestroy (ddata);
1105 }
1106
1107 /**
1108  * g_static_private_free:
1109  * @private_key: a #GStaticPrivate to be freed.
1110  *
1111  * Releases all resources allocated to @private_key.
1112  *
1113  * You don't have to call this functions for a #GStaticPrivate with an
1114  * unbounded lifetime, i.e. objects declared 'static', but if you have
1115  * a #GStaticPrivate as a member of a structure and the structure is
1116  * freed, you should also free the #GStaticPrivate.
1117  */
1118 void
1119 g_static_private_free (GStaticPrivate *private_key)
1120 {
1121   guint idx = private_key->index;
1122   GRealThread *thread, *next;
1123   GArray *garbage = NULL;
1124
1125   if (!idx)
1126     return;
1127
1128   private_key->index = 0;
1129
1130   G_LOCK (g_thread);
1131
1132   thread = g_thread_all_threads;
1133
1134   for (thread = g_thread_all_threads; thread; thread = next)
1135     {
1136       GArray *array;
1137
1138       next = thread->next;
1139
1140       LOCK_PRIVATE_DATA (thread);
1141
1142       array = thread->private_data;
1143
1144       if (array && idx <= array->len)
1145         {
1146           GStaticPrivateNode *node = &g_array_index (array,
1147                                                      GStaticPrivateNode,
1148                                                      idx - 1);
1149           gpointer ddata = node->data;
1150           GDestroyNotify ddestroy = node->destroy;
1151
1152           node->data = NULL;
1153           node->destroy = NULL;
1154
1155           if (ddestroy)
1156             {
1157               /* defer non-trivial destruction til after we've finished
1158                * iterating, since we must continue to hold the lock */
1159               if (garbage == NULL)
1160                 garbage = g_array_new (FALSE, TRUE,
1161                                        sizeof (GStaticPrivateNode));
1162
1163               g_array_set_size (garbage, garbage->len + 1);
1164
1165               node = &g_array_index (garbage, GStaticPrivateNode,
1166                                      garbage->len - 1);
1167               node->data = ddata;
1168               node->destroy = ddestroy;
1169             }
1170         }
1171
1172       UNLOCK_PRIVATE_DATA (thread);
1173     }
1174   g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1175                                            GUINT_TO_POINTER (idx));
1176   G_UNLOCK (g_thread);
1177
1178   if (garbage)
1179     {
1180       guint i;
1181
1182       for (i = 0; i < garbage->len; i++)
1183         {
1184           GStaticPrivateNode *node;
1185
1186           node = &g_array_index (garbage, GStaticPrivateNode, i);
1187           node->destroy (node->data);
1188         }
1189
1190       g_array_free (garbage, TRUE);
1191     }
1192 }
1193
1194 /* GThread Extra Functions {{{1 ------------------------------------------- */
1195 static void
1196 g_thread_cleanup (gpointer data)
1197 {
1198   if (data)
1199     {
1200       GRealThread* thread = data;
1201       GArray *array;
1202
1203       LOCK_PRIVATE_DATA (thread);
1204       array = thread->private_data;
1205       thread->private_data = NULL;
1206       UNLOCK_PRIVATE_DATA (thread);
1207
1208       if (array)
1209         {
1210           guint i;
1211
1212           for (i = 0; i < array->len; i++ )
1213             {
1214               GStaticPrivateNode *node =
1215                 &g_array_index (array, GStaticPrivateNode, i);
1216               if (node->destroy)
1217                 node->destroy (node->data);
1218             }
1219           g_array_free (array, TRUE);
1220         }
1221
1222       /* We only free the thread structure, if it isn't joinable. If
1223          it is, the structure is freed in g_thread_join */
1224       if (!thread->thread.joinable)
1225         {
1226           GRealThread *t, *p;
1227
1228           G_LOCK (g_thread);
1229           for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1230             {
1231               if (t == thread)
1232                 {
1233                   if (p)
1234                     p->next = t->next;
1235                   else
1236                     g_thread_all_threads = t->next;
1237                   break;
1238                 }
1239             }
1240           G_UNLOCK (g_thread);
1241
1242           /* Just to make sure, this isn't used any more */
1243           g_system_thread_assign (thread->system_thread, zero_thread);
1244           g_free (thread);
1245         }
1246     }
1247 }
1248
1249 static gpointer
1250 g_thread_create_proxy (gpointer data)
1251 {
1252   GRealThread* thread = data;
1253
1254   g_assert (data);
1255
1256   /* This has to happen before G_LOCK, as that might call g_thread_self */
1257   g_private_set (&g_thread_specific_private, data);
1258
1259   /* the lock makes sure, that thread->system_thread is written,
1260    * before thread->thread.func is called. See g_thread_create.
1261    */
1262   G_LOCK (g_thread);
1263   G_UNLOCK (g_thread);
1264
1265   thread->retval = thread->thread.func (thread->thread.data);
1266
1267   return NULL;
1268 }
1269
1270 /**
1271  * g_thread_create:
1272  * @func: a function to execute in the new thread
1273  * @data: an argument to supply to the new thread
1274  * @joinable: should this thread be joinable?
1275  * @error: return location for error, or %NULL
1276  *
1277  * This function creates a new thread.
1278  *
1279  * If @joinable is %TRUE, you can wait for this threads termination
1280  * calling g_thread_join(). Otherwise the thread will just disappear
1281  * when it terminates.
1282  *
1283  * The new thread executes the function @func with the argument @data.
1284  * If the thread was created successfully, it is returned.
1285  *
1286  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1287  * The error is set, if and only if the function returns %NULL.
1288  *
1289  * Returns: the new #GThread on success
1290  */
1291 GThread *
1292 g_thread_create (GThreadFunc   func,
1293                  gpointer      data,
1294                  gboolean      joinable,
1295                  GError      **error)
1296 {
1297   return g_thread_create_with_stack_size (func, data, joinable, 0, error);
1298 }
1299
1300 /**
1301  * g_thread_create_with_stack_size:
1302  * @func: a function to execute in the new thread.
1303  * @data: an argument to supply to the new thread.
1304  * @joinable: should this thread be joinable?
1305  * @stack_size: a stack size for the new thread.
1306  * @error: return location for error.
1307  * @Returns: the new #GThread on success.
1308  *
1309  * This function creates a new thread. If the underlying thread
1310  * implementation supports it, the thread gets a stack size of
1311  * @stack_size or the default value for the current platform, if
1312  * @stack_size is 0.
1313  *
1314  * If @joinable is %TRUE, you can wait for this threads termination
1315  * calling g_thread_join(). Otherwise the thread will just disappear
1316  * when it terminates.
1317  *
1318  * The new thread executes the function @func with the argument @data.
1319  * If the thread was created successfully, it is returned.
1320  *
1321  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1322  * The error is set, if and only if the function returns %NULL.
1323  *
1324  * <note><para>
1325  *   Only use g_thread_create_with_stack_size() if you really can't use
1326  *   g_thread_create() instead. g_thread_create() does not take
1327  *   @stack_size, as it should only be used in cases in which it is
1328  *   unavoidable.
1329  * </para></note>
1330  **/
1331 GThread*
1332 g_thread_create_with_stack_size (GThreadFunc   func,
1333                                  gpointer      data,
1334                                  gboolean      joinable,
1335                                  gsize         stack_size,
1336                                  GError      **error)
1337 {
1338   GRealThread* result;
1339   GError *local_error = NULL;
1340   g_return_val_if_fail (func, NULL);
1341
1342   result = g_new0 (GRealThread, 1);
1343
1344   result->thread.joinable = joinable;
1345   result->thread.func = func;
1346   result->thread.data = data;
1347   result->private_data = NULL;
1348   G_LOCK (g_thread);
1349   g_system_thread_create (g_thread_create_proxy, result,
1350                           stack_size, joinable,
1351                           &result->system_thread, &local_error);
1352   if (!local_error)
1353     {
1354       result->next = g_thread_all_threads;
1355       g_thread_all_threads = result;
1356     }
1357   G_UNLOCK (g_thread);
1358
1359   if (local_error)
1360     {
1361       g_propagate_error (error, local_error);
1362       g_free (result);
1363       return NULL;
1364     }
1365
1366   return (GThread*) result;
1367 }
1368
1369 /**
1370  * g_thread_exit:
1371  * @retval: the return value of this thread.
1372  *
1373  * Exits the current thread. If another thread is waiting for that
1374  * thread using g_thread_join() and the current thread is joinable, the
1375  * waiting thread will be woken up and get @retval as the return value
1376  * of g_thread_join(). If the current thread is not joinable, @retval
1377  * is ignored. Calling
1378  *
1379  * |[
1380  *   g_thread_exit (retval);
1381  * ]|
1382  *
1383  * is equivalent to returning @retval from the function @func, as given
1384  * to g_thread_create().
1385  *
1386  * <note><para>Never call g_thread_exit() from within a thread of a
1387  * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1388  * and unwanted results.</para></note>
1389  **/
1390 void
1391 g_thread_exit (gpointer retval)
1392 {
1393   GRealThread* real = (GRealThread*) g_thread_self ();
1394   real->retval = retval;
1395
1396   g_system_thread_exit ();
1397 }
1398
1399 /**
1400  * g_thread_join:
1401  * @thread: a #GThread to be waited for.
1402  * @Returns: the return value of the thread.
1403  *
1404  * Waits until @thread finishes, i.e. the function @func, as given to
1405  * g_thread_create(), returns or g_thread_exit() is called by @thread.
1406  * All resources of @thread including the #GThread struct are released.
1407  * @thread must have been created with @joinable=%TRUE in
1408  * g_thread_create(). The value returned by @func or given to
1409  * g_thread_exit() by @thread is returned by this function.
1410  **/
1411 gpointer
1412 g_thread_join (GThread* thread)
1413 {
1414   GRealThread* real = (GRealThread*) thread;
1415   GRealThread *p, *t;
1416   gpointer retval;
1417
1418   g_return_val_if_fail (thread, NULL);
1419   g_return_val_if_fail (thread->joinable, NULL);
1420   g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1421
1422   g_system_thread_join (&real->system_thread);
1423
1424   retval = real->retval;
1425
1426   G_LOCK (g_thread);
1427   for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1428     {
1429       if (t == (GRealThread*) thread)
1430         {
1431           if (p)
1432             p->next = t->next;
1433           else
1434             g_thread_all_threads = t->next;
1435           break;
1436         }
1437     }
1438   G_UNLOCK (g_thread);
1439
1440   /* Just to make sure, this isn't used any more */
1441   thread->joinable = 0;
1442   g_system_thread_assign (real->system_thread, zero_thread);
1443
1444   /* the thread structure for non-joinable threads is freed upon
1445    * thread end. We free the memory here. This will leave a loose end,
1446    * if a joinable thread is not joined.
1447    */
1448   g_free (thread);
1449
1450   return retval;
1451 }
1452
1453 /**
1454  * g_thread_self:
1455  * @Returns: the current thread.
1456  *
1457  * This functions returns the #GThread corresponding to the calling
1458  * thread.
1459  **/
1460 GThread*
1461 g_thread_self (void)
1462 {
1463   GRealThread* thread = g_private_get (&g_thread_specific_private);
1464
1465   if (!thread)
1466     {
1467       /* If no thread data is available, provide and set one.  This
1468          can happen for the main thread and for threads, that are not
1469          created by GLib. */
1470       thread = g_new0 (GRealThread, 1);
1471       thread->thread.joinable = FALSE; /* This is a save guess */
1472       thread->thread.func = NULL;
1473       thread->thread.data = NULL;
1474       thread->private_data = NULL;
1475
1476       g_system_thread_self (&thread->system_thread);
1477
1478       g_private_set (&g_thread_specific_private, thread);
1479
1480       G_LOCK (g_thread);
1481       thread->next = g_thread_all_threads;
1482       g_thread_all_threads = thread;
1483       G_UNLOCK (g_thread);
1484     }
1485
1486   return (GThread*)thread;
1487 }
1488
1489 /* Unsorted {{{1 ---------------------------------------------------------- */
1490
1491 /**
1492  * g_thread_foreach
1493  * @thread_func: function to call for all GThread structures
1494  * @user_data:   second argument to @thread_func
1495  *
1496  * Call @thread_func on all existing #GThread structures. Note that
1497  * threads may decide to exit while @thread_func is running, so
1498  * without intimate knowledge about the lifetime of foreign threads,
1499  * @thread_func shouldn't access the GThread* pointer passed in as
1500  * first argument. However, @thread_func will not be called for threads
1501  * which are known to have exited already.
1502  *
1503  * Due to thread lifetime checks, this function has an execution complexity
1504  * which is quadratic in the number of existing threads.
1505  *
1506  * Since: 2.10
1507  */
1508 void
1509 g_thread_foreach (GFunc    thread_func,
1510                   gpointer user_data)
1511 {
1512   GSList *slist = NULL;
1513   GRealThread *thread;
1514   g_return_if_fail (thread_func != NULL);
1515   /* snapshot the list of threads for iteration */
1516   G_LOCK (g_thread);
1517   for (thread = g_thread_all_threads; thread; thread = thread->next)
1518     slist = g_slist_prepend (slist, thread);
1519   G_UNLOCK (g_thread);
1520   /* walk the list, skipping non-existent threads */
1521   while (slist)
1522     {
1523       GSList *node = slist;
1524       slist = node->next;
1525       /* check whether the current thread still exists */
1526       G_LOCK (g_thread);
1527       for (thread = g_thread_all_threads; thread; thread = thread->next)
1528         if (thread == node->data)
1529           break;
1530       G_UNLOCK (g_thread);
1531       if (thread)
1532         thread_func (thread, user_data);
1533       g_slist_free_1 (node);
1534     }
1535 }
1536
1537 /**
1538  * g_thread_get_initialized:
1539  *
1540  * Indicates if g_thread_init() has been called.
1541  *
1542  * Returns: %TRUE if threads have been initialized.
1543  *
1544  * Since: 2.20
1545  */
1546 gboolean
1547 g_thread_get_initialized ()
1548 {
1549   return g_thread_supported ();
1550 }
1551
1552 /**
1553  * g_mutex_new:
1554  *
1555  * Allocated and initializes a new #GMutex.
1556  *
1557  * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
1558  */
1559 GMutex *
1560 g_mutex_new (void)
1561 {
1562   GMutex *mutex;
1563
1564   mutex = g_slice_new (GMutex);
1565   g_mutex_init (mutex);
1566
1567   return mutex;
1568 }
1569
1570 /**
1571  * g_mutex_free:
1572  * @mutex: a #GMutex
1573  *
1574  * Destroys a @mutex that has been created with g_mutex_new().
1575  *
1576  * Calling g_mutex_free() on a locked mutex may result
1577  * in undefined behaviour.
1578  */
1579 void
1580 g_mutex_free (GMutex *mutex)
1581 {
1582   g_mutex_clear (mutex);
1583   g_slice_free (GMutex, mutex);
1584 }
1585
1586 /**
1587  * g_cond_new:
1588  *
1589  * Allocates and initializes a new #GCond.
1590  *
1591  * Returns: a newly allocated #GCond. Free with g_cond_free()
1592  */
1593 GCond *
1594 g_cond_new (void)
1595 {
1596   GCond *cond;
1597
1598   cond = g_slice_new (GCond);
1599   g_cond_init (cond);
1600
1601   return cond;
1602 }
1603
1604 /**
1605  * g_cond_free:
1606  * @cond: a #GCond
1607  *
1608  * Destroys a #GCond that has been created with g_cond_new().
1609  */
1610 void
1611 g_cond_free (GCond *cond)
1612 {
1613   g_cond_clear (cond);
1614   g_slice_free (GCond, cond);
1615 }
1616
1617 /**
1618  * g_private_new:
1619  * @destructor: a function to destroy the data keyed to
1620  *     the #GPrivate when a thread ends
1621  *
1622  * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
1623  * pointer to a destructor function. Whenever a thread ends and the
1624  * corresponding pointer keyed to this instance of #GPrivate is
1625  * non-%NULL, the destructor is called with this pointer as the
1626  * argument.
1627  *
1628  * <note><para>
1629  * #GStaticPrivate is a better choice for most uses.
1630  * </para></note>
1631  *
1632  * <note><para>@destructor is used quite differently from @notify in
1633  * g_static_private_set().</para></note>
1634  *
1635  * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
1636  * can, to avoid shortage, or use #GStaticPrivate.</para></note>
1637  *
1638  * <note><para>This function will abort if g_thread_init() has not been
1639  * called yet.</para></note>
1640  *
1641  * Returns: a newly allocated #GPrivate
1642  */
1643 GPrivate *
1644 g_private_new (GDestroyNotify notify)
1645 {
1646   GPrivate *key;
1647
1648   key = g_slice_new (GPrivate);
1649   g_private_init (key, notify);
1650
1651   return key;
1652 }
1653
1654 /* vim: set foldmethod=marker: */