Remove g_thread_functions_for_glib_use_old
[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 "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: thread abstraction; including threads, different
71  *                     mutexes, 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, #GStaticMutex, #G_LOCK_DEFINE, #GStaticRecMutex and
88  * #GStaticRWLock). There is a facility to use individual bits for
89  * locks (g_bit_lock()). There are primitives for condition variables to
90  * allow synchronization of threads (#GCond).  There are primitives for
91  * thread-private data - data that every thread has a private instance
92  * of (#GPrivate, #GStaticPrivate). There are facilities for one-time
93  * initialization (#GOnce, g_once_init_enter()). Last but definitely
94  * not least there are primitives to portably create and manage
95  * threads (#GThread).
96  *
97  * The threading system is initialized with g_thread_init(), which
98  * takes an optional custom thread implementation or %NULL for the
99  * default implementation. If you want to call g_thread_init() with a
100  * non-%NULL argument this must be done before executing any other GLib
101  * functions (except g_mem_set_vtable()). This is a requirement even if
102  * no threads are in fact ever created by the process.
103  *
104  * Calling g_thread_init() with a %NULL argument is somewhat more
105  * relaxed. You may call any other glib functions in the main thread
106  * before g_thread_init() as long as g_thread_init() is not called from
107  * a glib callback, or with any locks held. However, many libraries
108  * above glib does not support late initialization of threads, so doing
109  * this should be avoided if possible.
110  *
111  * Please note that since version 2.24 the GObject initialization
112  * function g_type_init() initializes threads (with a %NULL argument),
113  * so most applications, including those using Gtk+ will run with
114  * threads enabled. If you want a special thread implementation, make
115  * sure you call g_thread_init() before g_type_init() is called.
116  *
117  * After calling g_thread_init(), GLib is completely thread safe (all
118  * global data is automatically locked), but individual data structure
119  * instances are not automatically locked for performance reasons. So,
120  * for example you must coordinate accesses to the same #GHashTable
121  * from multiple threads.  The two notable exceptions from this rule
122  * are #GMainLoop and #GAsyncQueue, which <emphasis>are</emphasis>
123  * threadsafe and need no further application-level locking to be
124  * accessed from multiple threads.
125  *
126  * To help debugging problems in multithreaded applications, GLib
127  * supports error-checking mutexes that will give you helpful error
128  * messages on common problems. To use error-checking mutexes, define
129  * the symbol #G_ERRORCHECK_MUTEXES when compiling the application.
130  **/
131
132 /**
133  * G_THREADS_IMPL_POSIX:
134  *
135  * This macro is defined if POSIX style threads are used.
136  **/
137
138 /**
139  * G_THREADS_ENABLED:
140  *
141  * This macro is defined, for backward compatibility, to indicate that
142  * GLib has been compiled with thread support. As of glib 2.28, it is
143  * always defined.
144  **/
145
146 /**
147  * G_THREADS_IMPL_NONE:
148  *
149  * This macro is defined if no thread implementation is used. You can,
150  * however, provide one to g_thread_init() to make GLib multi-thread
151  * safe.
152  **/
153
154 /* G_LOCK Documentation {{{1 ---------------------------------------------- */
155
156 /* IMPLEMENTATION NOTE:
157  *
158  * G_LOCK_DEFINE and friends are convenience macros defined in
159  * gthread.h.  Their documentation lives here.
160  */
161
162 /**
163  * G_LOCK_DEFINE:
164  * @name: the name of the lock.
165  *
166  * The %G_LOCK_* macros provide a convenient interface to #GStaticMutex
167  * with the advantage that they will expand to nothing in programs
168  * compiled against a thread-disabled GLib, saving code and memory
169  * there. #G_LOCK_DEFINE defines a lock. It can appear anywhere
170  * variable definitions may appear in programs, i.e. in the first block
171  * of a function or outside of functions. The @name parameter will be
172  * mangled to get the name of the #GStaticMutex. This means that you
173  * can use names of existing variables as the parameter - e.g. the name
174  * of the variable you intent to protect with the lock. Look at our
175  * <function>give_me_next_number()</function> example using the
176  * %G_LOCK_* macros:
177  *
178  * <example>
179  *  <title>Using the %G_LOCK_* convenience macros</title>
180  *  <programlisting>
181  *   G_LOCK_DEFINE (current_number);
182  *
183  *   int
184  *   give_me_next_number (void)
185  *   {
186  *     static int current_number = 0;
187  *     int ret_val;
188  *
189  *     G_LOCK (current_number);
190  *     ret_val = current_number = calc_next_number (current_number);
191  *     G_UNLOCK (current_number);
192  *
193  *     return ret_val;
194  *   }
195  *  </programlisting>
196  * </example>
197  **/
198
199 /**
200  * G_LOCK_DEFINE_STATIC:
201  * @name: the name of the lock.
202  *
203  * This works like #G_LOCK_DEFINE, but it creates a static object.
204  **/
205
206 /**
207  * G_LOCK_EXTERN:
208  * @name: the name of the lock.
209  *
210  * This declares a lock, that is defined with #G_LOCK_DEFINE in another
211  * module.
212  **/
213
214 /**
215  * G_LOCK:
216  * @name: the name of the lock.
217  *
218  * Works like g_mutex_lock(), but for a lock defined with
219  * #G_LOCK_DEFINE.
220  **/
221
222 /**
223  * G_TRYLOCK:
224  * @name: the name of the lock.
225  * @Returns: %TRUE, if the lock could be locked.
226  *
227  * Works like g_mutex_trylock(), but for a lock defined with
228  * #G_LOCK_DEFINE.
229  **/
230
231 /**
232  * G_UNLOCK:
233  * @name: the name of the lock.
234  *
235  * Works like g_mutex_unlock(), but for a lock defined with
236  * #G_LOCK_DEFINE.
237  **/
238
239 /* GThreadError {{{1 ------------------------------------------------------- */
240 /**
241  * GThreadError:
242  * @G_THREAD_ERROR_AGAIN: a thread couldn't be created due to resource
243  *                        shortage. Try again later.
244  *
245  * Possible errors of thread related functions.
246  **/
247
248 /**
249  * G_THREAD_ERROR:
250  *
251  * The error domain of the GLib thread subsystem.
252  **/
253 GQuark
254 g_thread_error_quark (void)
255 {
256   return g_quark_from_static_string ("g_thread_error");
257 }
258
259 /* Miscellaneous Structures {{{1 ------------------------------------------ */
260 typedef struct _GRealThread GRealThread;
261 struct  _GRealThread
262 {
263   GThread thread;
264   /* Bit 0 protects private_data. To avoid deadlocks, do not block while
265    * holding this (particularly on the g_thread lock). */
266   volatile gint private_data_lock;
267   GArray *private_data;
268   GRealThread *next;
269   gpointer retval;
270   GSystemThread system_thread;
271 };
272
273 #define LOCK_PRIVATE_DATA(self)   g_bit_lock (&(self)->private_data_lock, 0)
274 #define UNLOCK_PRIVATE_DATA(self) g_bit_unlock (&(self)->private_data_lock, 0)
275
276 typedef struct _GStaticPrivateNode GStaticPrivateNode;
277 struct _GStaticPrivateNode
278 {
279   gpointer       data;
280   GDestroyNotify destroy;
281 };
282
283 static void    g_thread_cleanup (gpointer data);
284 static void    g_thread_fail (void);
285 static guint64 gettime (void);
286
287 guint64        (*g_thread_gettime) (void) = gettime;
288
289 /* Global Variables {{{1 -------------------------------------------------- */
290
291 static GSystemThread zero_thread; /* This is initialized to all zero */
292 gboolean g_thread_use_default_impl = TRUE;
293
294 /**
295  * g_thread_supported:
296  * @Returns: %TRUE, if the thread system is initialized.
297  *
298  * This function returns %TRUE if the thread system is initialized, and
299  * %FALSE if it is not.
300  *
301  * <note><para>This function is actually a macro. Apart from taking the
302  * address of it you can however use it as if it was a
303  * function.</para></note>
304  **/
305
306 /* IMPLEMENTATION NOTE:
307  *
308  * g_thread_supported() is just returns g_threads_got_initialized
309  */
310 gboolean g_threads_got_initialized = FALSE;
311
312
313 /* Thread Implementation Virtual Function Table {{{1 ---------------------- */
314 /* Virtual Function Table Documentation {{{2 ------------------------------ */
315 /**
316  * GThreadFunctions:
317  * @mutex_new: virtual function pointer for g_mutex_new()
318  * @mutex_lock: virtual function pointer for g_mutex_lock()
319  * @mutex_trylock: virtual function pointer for g_mutex_trylock()
320  * @mutex_unlock: virtual function pointer for g_mutex_unlock()
321  * @mutex_free: virtual function pointer for g_mutex_free()
322  * @cond_new: virtual function pointer for g_cond_new()
323  * @cond_signal: virtual function pointer for g_cond_signal()
324  * @cond_broadcast: virtual function pointer for g_cond_broadcast()
325  * @cond_wait: virtual function pointer for g_cond_wait()
326  * @cond_timed_wait: virtual function pointer for g_cond_timed_wait()
327  * @cond_free: virtual function pointer for g_cond_free()
328  * @private_new: virtual function pointer for g_private_new()
329  * @private_get: virtual function pointer for g_private_get()
330  * @private_set: virtual function pointer for g_private_set()
331  * @thread_create: virtual function pointer for g_thread_create()
332  * @thread_yield: virtual function pointer for g_thread_yield()
333  * @thread_join: virtual function pointer for g_thread_join()
334  * @thread_exit: virtual function pointer for g_thread_exit()
335  * @thread_set_priority: virtual function pointer for
336  *                       g_thread_set_priority()
337  * @thread_self: virtual function pointer for g_thread_self()
338  * @thread_equal: used internally by recursive mutex locks and by some
339  *                assertion checks
340  *
341  * This function table is used by g_thread_init() to initialize the
342  * thread system. The functions in the table are directly used by their
343  * g_* prepended counterparts (described in this document).  For
344  * example, if you call g_mutex_new() then mutex_new() from the table
345  * provided to g_thread_init() will be called.
346  *
347  * <note><para>Do not use this struct unless you know what you are
348  * doing.</para></note>
349  **/
350
351 /* GMutex Virtual Functions {{{2 ------------------------------------------ */
352
353 /**
354  * GMutex:
355  *
356  * The #GMutex struct is an opaque data structure to represent a mutex
357  * (mutual exclusion). It can be used to protect data against shared
358  * access. Take for example the following function:
359  *
360  * <example>
361  *  <title>A function which will not work in a threaded environment</title>
362  *  <programlisting>
363  *   int
364  *   give_me_next_number (void)
365  *   {
366  *     static int current_number = 0;
367  *
368  *     /<!-- -->* now do a very complicated calculation to calculate the new
369  *      * number, this might for example be a random number generator
370  *      *<!-- -->/
371  *     current_number = calc_next_number (current_number);
372  *
373  *     return current_number;
374  *   }
375  *  </programlisting>
376  * </example>
377  *
378  * It is easy to see that this won't work in a multi-threaded
379  * application. There current_number must be protected against shared
380  * access. A first naive implementation would be:
381  *
382  * <example>
383  *  <title>The wrong way to write a thread-safe function</title>
384  *  <programlisting>
385  *   int
386  *   give_me_next_number (void)
387  *   {
388  *     static int current_number = 0;
389  *     int ret_val;
390  *     static GMutex * mutex = NULL;
391  *
392  *     if (!mutex) mutex = g_mutex_new (<!-- -->);
393  *
394  *     g_mutex_lock (mutex);
395  *     ret_val = current_number = calc_next_number (current_number);
396  *     g_mutex_unlock (mutex);
397  *
398  *     return ret_val;
399  *   }
400  *  </programlisting>
401  * </example>
402  *
403  * This looks like it would work, but there is a race condition while
404  * constructing the mutex and this code cannot work reliable. Please do
405  * not use such constructs in your own programs! One working solution
406  * is:
407  *
408  * <example>
409  *  <title>A correct thread-safe function</title>
410  *  <programlisting>
411  *   static GMutex *give_me_next_number_mutex = NULL;
412  *
413  *   /<!-- -->* this function must be called before any call to
414  *    * give_me_next_number(<!-- -->)
415  *    *
416  *    * it must be called exactly once.
417  *    *<!-- -->/
418  *   void
419  *   init_give_me_next_number (void)
420  *   {
421  *     g_assert (give_me_next_number_mutex == NULL);
422  *     give_me_next_number_mutex = g_mutex_new (<!-- -->);
423  *   }
424  *
425  *   int
426  *   give_me_next_number (void)
427  *   {
428  *     static int current_number = 0;
429  *     int ret_val;
430  *
431  *     g_mutex_lock (give_me_next_number_mutex);
432  *     ret_val = current_number = calc_next_number (current_number);
433  *     g_mutex_unlock (give_me_next_number_mutex);
434  *
435  *     return ret_val;
436  *   }
437  *  </programlisting>
438  * </example>
439  *
440  * #GStaticMutex provides a simpler and safer way of doing this.
441  *
442  * If you want to use a mutex, and your code should also work without
443  * calling g_thread_init() first, then you cannot use a #GMutex, as
444  * g_mutex_new() requires that the thread system be initialized. Use a
445  * #GStaticMutex instead.
446  *
447  * A #GMutex should only be accessed via the following functions.
448  **/
449
450 /* GCond Virtual Functions {{{2 ------------------------------------------ */
451
452 /**
453  * GCond:
454  *
455  * The #GCond struct is an opaque data structure that represents a
456  * condition. Threads can block on a #GCond if they find a certain
457  * condition to be false. If other threads change the state of this
458  * condition they signal the #GCond, and that causes the waiting
459  * threads to be woken up.
460  *
461  * <example>
462  *  <title>
463  *   Using GCond to block a thread until a condition is satisfied
464  *  </title>
465  *  <programlisting>
466  *   GCond* data_cond = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
467  *   GMutex* data_mutex = NULL; /<!-- -->* Must be initialized somewhere *<!-- -->/
468  *   gpointer current_data = NULL;
469  *
470  *   void
471  *   push_data (gpointer data)
472  *   {
473  *     g_mutex_lock (data_mutex);
474  *     current_data = data;
475  *     g_cond_signal (data_cond);
476  *     g_mutex_unlock (data_mutex);
477  *   }
478  *
479  *   gpointer
480  *   pop_data (void)
481  *   {
482  *     gpointer data;
483  *
484  *     g_mutex_lock (data_mutex);
485  *     while (!current_data)
486  *       g_cond_wait (data_cond, data_mutex);
487  *     data = current_data;
488  *     current_data = NULL;
489  *     g_mutex_unlock (data_mutex);
490  *
491  *     return data;
492  *   }
493  *  </programlisting>
494  * </example>
495  *
496  * Whenever a thread calls <function>pop_data()</function> now, it will
497  * wait until current_data is non-%NULL, i.e. until some other thread
498  * has called <function>push_data()</function>.
499  *
500  * <note><para>It is important to use the g_cond_wait() and
501  * g_cond_timed_wait() functions only inside a loop which checks for the
502  * condition to be true.  It is not guaranteed that the waiting thread
503  * will find the condition fulfilled after it wakes up, even if the
504  * signaling thread left the condition in that state: another thread may
505  * have altered the condition before the waiting thread got the chance
506  * to be woken up, even if the condition itself is protected by a
507  * #GMutex, like above.</para></note>
508  *
509  * A #GCond should only be accessed via the following functions.
510  */
511
512 /* GPrivate Virtual Functions {{{2 --------------------------------------- */
513
514 /**
515  * GPrivate:
516  *
517  * <note><para>
518  * #GStaticPrivate is a better choice for most uses.
519  * </para></note>
520  *
521  * The #GPrivate struct is an opaque data structure to represent a
522  * thread private data key. Threads can thereby obtain and set a
523  * pointer which is private to the current thread. Take our
524  * <function>give_me_next_number(<!-- -->)</function> example from
525  * above.  Suppose we don't want <literal>current_number</literal> to be
526  * shared between the threads, but instead to be private to each thread.
527  * This can be done as follows:
528  *
529  * <example>
530  *  <title>Using GPrivate for per-thread data</title>
531  *  <programlisting>
532  *   GPrivate* current_number_key = NULL; /<!-- -->* Must be initialized somewhere
533  *                                           with g_private_new (g_free); *<!-- -->/
534  *
535  *   int
536  *   give_me_next_number (void)
537  *   {
538  *     int *current_number = g_private_get (current_number_key);
539  *
540  *     if (!current_number)
541  *       {
542  *         current_number = g_new (int, 1);
543  *         *current_number = 0;
544  *         g_private_set (current_number_key, current_number);
545  *       }
546  *
547  *     *current_number = calc_next_number (*current_number);
548  *
549  *     return *current_number;
550  *   }
551  *  </programlisting>
552  * </example>
553  *
554  * Here the pointer belonging to the key
555  * <literal>current_number_key</literal> is read. If it is %NULL, it has
556  * not been set yet. Then get memory for an integer value, assign this
557  * memory to the pointer and write the pointer back. Now we have an
558  * integer value that is private to the current thread.
559  *
560  * The #GPrivate struct should only be accessed via the following
561  * functions.
562  *
563  * <note><para>All of the <function>g_private_*</function> functions are
564  * actually macros. Apart from taking their addresses, you can however
565  * use them as if they were functions.</para></note>
566  **/
567
568 /* GThread Virtual Functions {{{2 ---------------------------------------- */
569 /**
570  * GThread:
571  *
572  * The #GThread struct represents a running thread. It has three public
573  * read-only members, but the underlying struct is bigger, so you must
574  * not copy this struct.
575  *
576  * <note><para>Resources for a joinable thread are not fully released
577  * until g_thread_join() is called for that thread.</para></note>
578  **/
579
580 /**
581  * GThreadFunc:
582  * @data: data passed to the thread.
583  * @Returns: the return value of the thread, which will be returned by
584  *           g_thread_join().
585  *
586  * Specifies the type of the @func functions passed to
587  * g_thread_create() or g_thread_create_full().
588  **/
589
590 /**
591  * GThreadPriority:
592  * @G_THREAD_PRIORITY_LOW: a priority lower than normal
593  * @G_THREAD_PRIORITY_NORMAL: the default priority
594  * @G_THREAD_PRIORITY_HIGH: a priority higher than normal
595  * @G_THREAD_PRIORITY_URGENT: the highest priority
596  *
597  * Deprecated:2.32: thread priorities no longer have any effect.
598  **/
599
600 /* Local Data {{{1 -------------------------------------------------------- */
601
602 static GMutex    g_once_mutex = G_MUTEX_INIT;
603 static GCond     g_once_cond = G_COND_INIT;
604 static GPrivate  g_thread_specific_private;
605 static GRealThread *g_thread_all_threads = NULL;
606 static GSList   *g_thread_free_indices = NULL;
607 static GSList*   g_once_init_list = NULL;
608
609 G_LOCK_DEFINE_STATIC (g_thread);
610
611 /* Initialisation {{{1 ---------------------------------------------------- */
612
613 /**
614  * g_thread_init:
615  * @vtable: a function table of type #GThreadFunctions, that provides
616  *          the entry points to the thread system to be used.
617  *
618  * If you use GLib from more than one thread, you must initialize the
619  * thread system by calling g_thread_init(). Most of the time you will
620  * only have to call <literal>g_thread_init (NULL)</literal>.
621  *
622  * <note><para>Do not call g_thread_init() with a non-%NULL parameter unless
623  * you really know what you are doing.</para></note>
624  *
625  * <note><para>g_thread_init() must not be called directly or indirectly as a
626  * callback from GLib. Also no mutexes may be currently locked while
627  * calling g_thread_init().</para></note>
628  *
629  * <note><para>g_thread_init() changes the way in which #GTimer measures
630  * elapsed time. As a consequence, timers that are running while
631  * g_thread_init() is called may report unreliable times.</para></note>
632  *
633  * Calling g_thread_init() multiple times is allowed (since version
634  * 2.24), but nothing happens except for the first call. If the
635  * argument is non-%NULL on such a call a warning will be printed, but
636  * otherwise the argument is ignored.
637  *
638  * If no thread system is available and @vtable is %NULL or if not all
639  * elements of @vtable are non-%NULL, then g_thread_init() will abort.
640  *
641  * <note><para>To use g_thread_init() in your program, you have to link with
642  * the libraries that the command <command>pkg-config --libs
643  * gthread-2.0</command> outputs. This is not the case for all the
644  * other thread related functions of GLib. Those can be used without
645  * having to link with the thread libraries.</para></note>
646  **/
647
648 /* This must be called only once, before any threads are created.
649  * It will only be called from g_thread_init() in -lgthread.
650  */
651 void
652 g_thread_init_glib (void)
653 {
654   static gboolean already_done;
655
656   if (already_done)
657     return;
658
659   already_done = TRUE;
660
661   _g_thread_impl_init ();
662
663   /* We let the main thread (the one that calls g_thread_init) inherit
664    * the static_private data set before calling g_thread_init
665    */
666   GRealThread* main_thread = (GRealThread*) g_thread_self ();
667
668   /* setup the basic threading system */
669   g_threads_got_initialized = TRUE;
670   g_private_init (&g_thread_specific_private, g_thread_cleanup);
671   g_private_set (&g_thread_specific_private, main_thread);
672   g_system_thread_self (&main_thread->system_thread);
673
674   /* accomplish log system initialization to enable messaging */
675   _g_messages_thread_init_nomessage ();
676 }
677
678 /* The following sections implement: GOnce, GStaticMutex, GStaticRecMutex,
679  * GStaticPrivate, 
680  **/
681
682 /* GOnce {{{1 ------------------------------------------------------------- */
683
684 /**
685  * GOnce:
686  * @status: the status of the #GOnce
687  * @retval: the value returned by the call to the function, if @status
688  *          is %G_ONCE_STATUS_READY
689  *
690  * A #GOnce struct controls a one-time initialization function. Any
691  * one-time initialization function must have its own unique #GOnce
692  * struct.
693  *
694  * Since: 2.4
695  **/
696
697 /**
698  * G_ONCE_INIT:
699  *
700  * A #GOnce must be initialized with this macro before it can be used.
701  *
702  * <informalexample>
703  *  <programlisting>
704  *   GOnce my_once = G_ONCE_INIT;
705  *  </programlisting>
706  * </informalexample>
707  *
708  * Since: 2.4
709  **/
710
711 /**
712  * GOnceStatus:
713  * @G_ONCE_STATUS_NOTCALLED: the function has not been called yet.
714  * @G_ONCE_STATUS_PROGRESS: the function call is currently in progress.
715  * @G_ONCE_STATUS_READY: the function has been called.
716  *
717  * The possible statuses of a one-time initialization function
718  * controlled by a #GOnce struct.
719  *
720  * Since: 2.4
721  **/
722
723 /**
724  * g_once:
725  * @once: a #GOnce structure
726  * @func: the #GThreadFunc function associated to @once. This function
727  *        is called only once, regardless of the number of times it and
728  *        its associated #GOnce struct are passed to g_once().
729  * @arg: data to be passed to @func
730  *
731  * The first call to this routine by a process with a given #GOnce
732  * struct calls @func with the given argument. Thereafter, subsequent
733  * calls to g_once()  with the same #GOnce struct do not call @func
734  * again, but return the stored result of the first call. On return
735  * from g_once(), the status of @once will be %G_ONCE_STATUS_READY.
736  *
737  * For example, a mutex or a thread-specific data key must be created
738  * exactly once. In a threaded environment, calling g_once() ensures
739  * that the initialization is serialized across multiple threads.
740  *
741  * <note><para>Calling g_once() recursively on the same #GOnce struct in
742  * @func will lead to a deadlock.</para></note>
743  *
744  * <informalexample>
745  *  <programlisting>
746  *   gpointer
747  *   get_debug_flags (void)
748  *   {
749  *     static GOnce my_once = G_ONCE_INIT;
750  *
751  *     g_once (&my_once, parse_debug_flags, NULL);
752  *
753  *     return my_once.retval;
754  *   }
755  *  </programlisting>
756  * </informalexample>
757  *
758  * Since: 2.4
759  **/
760 gpointer
761 g_once_impl (GOnce       *once,
762              GThreadFunc  func,
763              gpointer     arg)
764 {
765   g_mutex_lock (&g_once_mutex);
766
767   while (once->status == G_ONCE_STATUS_PROGRESS)
768     g_cond_wait (&g_once_cond, &g_once_mutex);
769
770   if (once->status != G_ONCE_STATUS_READY)
771     {
772       once->status = G_ONCE_STATUS_PROGRESS;
773       g_mutex_unlock (&g_once_mutex);
774
775       once->retval = func (arg);
776
777       g_mutex_lock (&g_once_mutex);
778       once->status = G_ONCE_STATUS_READY;
779       g_cond_broadcast (&g_once_cond);
780     }
781
782   g_mutex_unlock (&g_once_mutex);
783
784   return once->retval;
785 }
786
787 /**
788  * g_once_init_enter:
789  * @value_location: location of a static initializable variable
790  *                  containing 0.
791  * @Returns: %TRUE if the initialization section should be entered,
792  *           %FALSE and blocks otherwise
793  *
794  * Function to be called when starting a critical initialization
795  * section. The argument @value_location must point to a static
796  * 0-initialized variable that will be set to a value other than 0 at
797  * the end of the initialization section. In combination with
798  * g_once_init_leave() and the unique address @value_location, it can
799  * be ensured that an initialization section will be executed only once
800  * during a program's life time, and that concurrent threads are
801  * blocked until initialization completed. To be used in constructs
802  * like this:
803  *
804  * <informalexample>
805  *  <programlisting>
806  *   static gsize initialization_value = 0;
807  *
808  *   if (g_once_init_enter (&amp;initialization_value))
809  *     {
810  *       gsize setup_value = 42; /<!-- -->* initialization code here *<!-- -->/
811  *
812  *       g_once_init_leave (&amp;initialization_value, setup_value);
813  *     }
814  *
815  *   /<!-- -->* use initialization_value here *<!-- -->/
816  *  </programlisting>
817  * </informalexample>
818  *
819  * Since: 2.14
820  **/
821 gboolean
822 g_once_init_enter_impl (volatile gsize *value_location)
823 {
824   gboolean need_init = FALSE;
825   g_mutex_lock (&g_once_mutex);
826   if (g_atomic_pointer_get (value_location) == NULL)
827     {
828       if (!g_slist_find (g_once_init_list, (void*) value_location))
829         {
830           need_init = TRUE;
831           g_once_init_list = g_slist_prepend (g_once_init_list, (void*) value_location);
832         }
833       else
834         do
835           g_cond_wait (&g_once_cond, &g_once_mutex);
836         while (g_slist_find (g_once_init_list, (void*) value_location));
837     }
838   g_mutex_unlock (&g_once_mutex);
839   return need_init;
840 }
841
842 /**
843  * g_once_init_leave:
844  * @value_location: location of a static initializable variable
845  *                  containing 0.
846  * @initialization_value: new non-0 value for *@value_location.
847  *
848  * Counterpart to g_once_init_enter(). Expects a location of a static
849  * 0-initialized initialization variable, and an initialization value
850  * other than 0. Sets the variable to the initialization value, and
851  * releases concurrent threads blocking in g_once_init_enter() on this
852  * initialization variable.
853  *
854  * Since: 2.14
855  **/
856 void
857 g_once_init_leave (volatile gsize *value_location,
858                    gsize           initialization_value)
859 {
860   g_return_if_fail (g_atomic_pointer_get (value_location) == NULL);
861   g_return_if_fail (initialization_value != 0);
862   g_return_if_fail (g_once_init_list != NULL);
863
864   g_atomic_pointer_set (value_location, initialization_value);
865   g_mutex_lock (&g_once_mutex);
866   g_once_init_list = g_slist_remove (g_once_init_list, (void*) value_location);
867   g_cond_broadcast (&g_once_cond);
868   g_mutex_unlock (&g_once_mutex);
869 }
870
871 /* GStaticMutex {{{1 ------------------------------------------------------ */
872
873 /**
874  * GStaticMutex:
875  *
876  * A #GStaticMutex works like a #GMutex, but it has one significant
877  * advantage. It doesn't need to be created at run-time like a #GMutex,
878  * but can be defined at compile-time. Here is a shorter, easier and
879  * safer version of our <function>give_me_next_number()</function>
880  * example:
881  *
882  * <example>
883  *  <title>
884  *   Using <structname>GStaticMutex</structname>
885  *   to simplify thread-safe programming
886  *  </title>
887  *  <programlisting>
888  *   int
889  *   give_me_next_number (void)
890  *   {
891  *     static int current_number = 0;
892  *     int ret_val;
893  *     static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
894  *
895  *     g_static_mutex_lock (&amp;mutex);
896  *     ret_val = current_number = calc_next_number (current_number);
897  *     g_static_mutex_unlock (&amp;mutex);
898  *
899  *     return ret_val;
900  *   }
901  *  </programlisting>
902  * </example>
903  *
904  * Sometimes you would like to dynamically create a mutex. If you don't
905  * want to require prior calling to g_thread_init(), because your code
906  * should also be usable in non-threaded programs, you are not able to
907  * use g_mutex_new() and thus #GMutex, as that requires a prior call to
908  * g_thread_init(). In theses cases you can also use a #GStaticMutex.
909  * It must be initialized with g_static_mutex_init() before using it
910  * and freed with with g_static_mutex_free() when not needed anymore to
911  * free up any allocated resources.
912  *
913  * Even though #GStaticMutex is not opaque, it should only be used with
914  * the following functions, as it is defined differently on different
915  * platforms.
916  *
917  * All of the <function>g_static_mutex_*</function> functions apart
918  * from <function>g_static_mutex_get_mutex</function> can also be used
919  * even if g_thread_init() has not yet been called. Then they do
920  * nothing, apart from <function>g_static_mutex_trylock</function>,
921  * which does nothing but returning %TRUE.
922  *
923  * <note><para>All of the <function>g_static_mutex_*</function>
924  * functions are actually macros. Apart from taking their addresses, you
925  * can however use them as if they were functions.</para></note>
926  **/
927
928 /**
929  * G_STATIC_MUTEX_INIT:
930  *
931  * A #GStaticMutex must be initialized with this macro, before it can
932  * be used. This macro can used be to initialize a variable, but it
933  * cannot be assigned to a variable. In that case you have to use
934  * g_static_mutex_init().
935  *
936  * <informalexample>
937  *  <programlisting>
938  *   GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;
939  *  </programlisting>
940  * </informalexample>
941  **/
942
943 /**
944  * g_static_mutex_init:
945  * @mutex: a #GStaticMutex to be initialized.
946  *
947  * Initializes @mutex. Alternatively you can initialize it with
948  * #G_STATIC_MUTEX_INIT.
949  **/
950 void
951 g_static_mutex_init (GStaticMutex *mutex)
952 {
953   static const GStaticMutex init_mutex = G_STATIC_MUTEX_INIT;
954
955   g_return_if_fail (mutex);
956
957   *mutex = init_mutex;
958 }
959
960 /* IMPLEMENTATION NOTE:
961  *
962  * On some platforms a GStaticMutex is actually a normal GMutex stored
963  * inside of a structure instead of being allocated dynamically.  We can
964  * only do this for platforms on which we know, in advance, how to
965  * allocate (size) and initialise (value) that memory.
966  *
967  * On other platforms, a GStaticMutex is nothing more than a pointer to
968  * a GMutex.  In that case, the first access we make to the static mutex
969  * must first allocate the normal GMutex and store it into the pointer.
970  *
971  * configure.ac writes macros into glibconfig.h to determine if
972  * g_static_mutex_get_mutex() accesses the structure in memory directly
973  * (on platforms where we are able to do that) or if it ends up here,
974  * where we may have to allocate the GMutex before returning it.
975  */
976
977 /**
978  * g_static_mutex_get_mutex:
979  * @mutex: a #GStaticMutex.
980  * @Returns: the #GMutex corresponding to @mutex.
981  *
982  * For some operations (like g_cond_wait()) you must have a #GMutex
983  * instead of a #GStaticMutex. This function will return the
984  * corresponding #GMutex for @mutex.
985  **/
986 GMutex *
987 g_static_mutex_get_mutex_impl (GMutex** mutex)
988 {
989   GMutex *result;
990
991   if (!g_thread_supported ())
992     return NULL;
993
994   result = g_atomic_pointer_get (mutex);
995
996   if (!result)
997     {
998       g_mutex_lock (&g_once_mutex);
999
1000       result = *mutex;
1001       if (!result)
1002         {
1003           result = g_mutex_new ();
1004           g_atomic_pointer_set (mutex, result);
1005         }
1006
1007       g_mutex_unlock (&g_once_mutex);
1008     }
1009
1010   return result;
1011 }
1012
1013 /* IMPLEMENTATION NOTE:
1014  *
1015  * g_static_mutex_lock(), g_static_mutex_trylock() and
1016  * g_static_mutex_unlock() are all preprocessor macros that wrap the
1017  * corresponding g_mutex_*() function around a call to
1018  * g_static_mutex_get_mutex().
1019  */
1020
1021 /**
1022  * g_static_mutex_lock:
1023  * @mutex: a #GStaticMutex.
1024  *
1025  * Works like g_mutex_lock(), but for a #GStaticMutex.
1026  **/
1027
1028 /**
1029  * g_static_mutex_trylock:
1030  * @mutex: a #GStaticMutex.
1031  * @Returns: %TRUE, if the #GStaticMutex could be locked.
1032  *
1033  * Works like g_mutex_trylock(), but for a #GStaticMutex.
1034  **/
1035
1036 /**
1037  * g_static_mutex_unlock:
1038  * @mutex: a #GStaticMutex.
1039  *
1040  * Works like g_mutex_unlock(), but for a #GStaticMutex.
1041  **/
1042
1043 /**
1044  * g_static_mutex_free:
1045  * @mutex: a #GStaticMutex to be freed.
1046  *
1047  * Releases all resources allocated to @mutex.
1048  *
1049  * You don't have to call this functions for a #GStaticMutex with an
1050  * unbounded lifetime, i.e. objects declared 'static', but if you have
1051  * a #GStaticMutex as a member of a structure and the structure is
1052  * freed, you should also free the #GStaticMutex.
1053  *
1054  * <note><para>Calling g_static_mutex_free() on a locked mutex may
1055  * result in undefined behaviour.</para></note>
1056  **/
1057 void
1058 g_static_mutex_free (GStaticMutex* mutex)
1059 {
1060   GMutex **runtime_mutex;
1061
1062   g_return_if_fail (mutex);
1063
1064   /* The runtime_mutex is the first (or only) member of GStaticMutex,
1065    * see both versions (of glibconfig.h) in configure.ac. Note, that
1066    * this variable is NULL, if g_thread_init() hasn't been called or
1067    * if we're using the default thread implementation and it provides
1068    * static mutexes. */
1069   runtime_mutex = ((GMutex**)mutex);
1070
1071   if (*runtime_mutex)
1072     g_mutex_free (*runtime_mutex);
1073
1074   *runtime_mutex = NULL;
1075 }
1076
1077 /* ------------------------------------------------------------------------ */
1078
1079 /**
1080  * GStaticRecMutex:
1081  *
1082  * A #GStaticRecMutex works like a #GStaticMutex, but it can be locked
1083  * multiple times by one thread. If you enter it n times, you have to
1084  * unlock it n times again to let other threads lock it. An exception
1085  * is the function g_static_rec_mutex_unlock_full(): that allows you to
1086  * unlock a #GStaticRecMutex completely returning the depth, (i.e. the
1087  * number of times this mutex was locked). The depth can later be used
1088  * to restore the state of the #GStaticRecMutex by calling
1089  * g_static_rec_mutex_lock_full().
1090  *
1091  * Even though #GStaticRecMutex is not opaque, it should only be used
1092  * with the following functions.
1093  *
1094  * All of the <function>g_static_rec_mutex_*</function> functions can
1095  * be used even if g_thread_init() has not been called. Then they do
1096  * nothing, apart from <function>g_static_rec_mutex_trylock</function>,
1097  * which does nothing but returning %TRUE.
1098  **/
1099
1100 /**
1101  * G_STATIC_REC_MUTEX_INIT:
1102  *
1103  * A #GStaticRecMutex must be initialized with this macro before it can
1104  * be used. This macro can used be to initialize a variable, but it
1105  * cannot be assigned to a variable. In that case you have to use
1106  * g_static_rec_mutex_init().
1107  *
1108  * <informalexample>
1109  *  <programlisting>
1110  *   GStaticRecMutex my_mutex = G_STATIC_REC_MUTEX_INIT;
1111  * </programlisting>
1112  </informalexample>
1113  **/
1114
1115 /**
1116  * g_static_rec_mutex_init:
1117  * @mutex: a #GStaticRecMutex to be initialized.
1118  *
1119  * A #GStaticRecMutex must be initialized with this function before it
1120  * can be used. Alternatively you can initialize it with
1121  * #G_STATIC_REC_MUTEX_INIT.
1122  **/
1123 void
1124 g_static_rec_mutex_init (GStaticRecMutex *mutex)
1125 {
1126   static const GStaticRecMutex init_mutex = G_STATIC_REC_MUTEX_INIT;
1127
1128   g_return_if_fail (mutex);
1129
1130   *mutex = init_mutex;
1131 }
1132
1133 /**
1134  * g_static_rec_mutex_lock:
1135  * @mutex: a #GStaticRecMutex to lock.
1136  *
1137  * Locks @mutex. If @mutex is already locked by another thread, the
1138  * current thread will block until @mutex is unlocked by the other
1139  * thread. If @mutex is already locked by the calling thread, this
1140  * functions increases the depth of @mutex and returns immediately.
1141  **/
1142 void
1143 g_static_rec_mutex_lock (GStaticRecMutex* mutex)
1144 {
1145   GSystemThread self;
1146
1147   g_return_if_fail (mutex);
1148
1149   if (!g_thread_supported ())
1150     return;
1151
1152   g_system_thread_self (&self);
1153
1154   if (g_system_thread_equal (&self, &mutex->owner))
1155     {
1156       mutex->depth++;
1157       return;
1158     }
1159   g_static_mutex_lock (&mutex->mutex);
1160   g_system_thread_assign (mutex->owner, self);
1161   mutex->depth = 1;
1162 }
1163
1164 /**
1165  * g_static_rec_mutex_trylock:
1166  * @mutex: a #GStaticRecMutex to lock.
1167  * @Returns: %TRUE, if @mutex could be locked.
1168  *
1169  * Tries to lock @mutex. If @mutex is already locked by another thread,
1170  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
1171  * %TRUE. If @mutex is already locked by the calling thread, this
1172  * functions increases the depth of @mutex and immediately returns
1173  * %TRUE.
1174  **/
1175 gboolean
1176 g_static_rec_mutex_trylock (GStaticRecMutex* mutex)
1177 {
1178   GSystemThread self;
1179
1180   g_return_val_if_fail (mutex, FALSE);
1181
1182   if (!g_thread_supported ())
1183     return TRUE;
1184
1185   g_system_thread_self (&self);
1186
1187   if (g_system_thread_equal (&self, &mutex->owner))
1188     {
1189       mutex->depth++;
1190       return TRUE;
1191     }
1192
1193   if (!g_static_mutex_trylock (&mutex->mutex))
1194     return FALSE;
1195
1196   g_system_thread_assign (mutex->owner, self);
1197   mutex->depth = 1;
1198   return TRUE;
1199 }
1200
1201 /**
1202  * g_static_rec_mutex_unlock:
1203  * @mutex: a #GStaticRecMutex to unlock.
1204  *
1205  * Unlocks @mutex. Another thread will be allowed to lock @mutex only
1206  * when it has been unlocked as many times as it had been locked
1207  * before. If @mutex is completely unlocked and another thread is
1208  * blocked in a g_static_rec_mutex_lock() call for @mutex, it will be
1209  * woken and can lock @mutex itself.
1210  **/
1211 void
1212 g_static_rec_mutex_unlock (GStaticRecMutex* mutex)
1213 {
1214   g_return_if_fail (mutex);
1215
1216   if (!g_thread_supported ())
1217     return;
1218
1219   if (mutex->depth > 1)
1220     {
1221       mutex->depth--;
1222       return;
1223     }
1224   g_system_thread_assign (mutex->owner, zero_thread);
1225   g_static_mutex_unlock (&mutex->mutex);
1226 }
1227
1228 /**
1229  * g_static_rec_mutex_lock_full:
1230  * @mutex: a #GStaticRecMutex to lock.
1231  * @depth: number of times this mutex has to be unlocked to be
1232  *         completely unlocked.
1233  *
1234  * Works like calling g_static_rec_mutex_lock() for @mutex @depth times.
1235  **/
1236 void
1237 g_static_rec_mutex_lock_full   (GStaticRecMutex *mutex,
1238                                 guint            depth)
1239 {
1240   GSystemThread self;
1241   g_return_if_fail (mutex);
1242
1243   if (!g_thread_supported ())
1244     return;
1245
1246   if (depth == 0)
1247     return;
1248
1249   g_system_thread_self (&self);
1250
1251   if (g_system_thread_equal (&self, &mutex->owner))
1252     {
1253       mutex->depth += depth;
1254       return;
1255     }
1256   g_static_mutex_lock (&mutex->mutex);
1257   g_system_thread_assign (mutex->owner, self);
1258   mutex->depth = depth;
1259 }
1260
1261 /**
1262  * g_static_rec_mutex_unlock_full:
1263  * @mutex: a #GStaticRecMutex to completely unlock.
1264  * @Returns: number of times @mutex has been locked by the current
1265  *           thread.
1266  *
1267  * Completely unlocks @mutex. If another thread is blocked in a
1268  * g_static_rec_mutex_lock() call for @mutex, it will be woken and can
1269  * lock @mutex itself. This function returns the number of times that
1270  * @mutex has been locked by the current thread. To restore the state
1271  * before the call to g_static_rec_mutex_unlock_full() you can call
1272  * g_static_rec_mutex_lock_full() with the depth returned by this
1273  * function.
1274  **/
1275 guint
1276 g_static_rec_mutex_unlock_full (GStaticRecMutex *mutex)
1277 {
1278   guint depth;
1279
1280   g_return_val_if_fail (mutex, 0);
1281
1282   if (!g_thread_supported ())
1283     return 1;
1284
1285   depth = mutex->depth;
1286
1287   g_system_thread_assign (mutex->owner, zero_thread);
1288   mutex->depth = 0;
1289   g_static_mutex_unlock (&mutex->mutex);
1290
1291   return depth;
1292 }
1293
1294 /**
1295  * g_static_rec_mutex_free:
1296  * @mutex: a #GStaticRecMutex to be freed.
1297  *
1298  * Releases all resources allocated to a #GStaticRecMutex.
1299  *
1300  * You don't have to call this functions for a #GStaticRecMutex with an
1301  * unbounded lifetime, i.e. objects declared 'static', but if you have
1302  * a #GStaticRecMutex as a member of a structure and the structure is
1303  * freed, you should also free the #GStaticRecMutex.
1304  **/
1305 void
1306 g_static_rec_mutex_free (GStaticRecMutex *mutex)
1307 {
1308   g_return_if_fail (mutex);
1309
1310   g_static_mutex_free (&mutex->mutex);
1311 }
1312
1313 /* GStaticPrivate {{{1 ---------------------------------------------------- */
1314
1315 /**
1316  * GStaticPrivate:
1317  *
1318  * A #GStaticPrivate works almost like a #GPrivate, but it has one
1319  * significant advantage. It doesn't need to be created at run-time
1320  * like a #GPrivate, but can be defined at compile-time. This is
1321  * similar to the difference between #GMutex and #GStaticMutex. Now
1322  * look at our <function>give_me_next_number()</function> example with
1323  * #GStaticPrivate:
1324  *
1325  * <example>
1326  *  <title>Using GStaticPrivate for per-thread data</title>
1327  *  <programlisting>
1328  *   int
1329  *   give_me_next_number (<!-- -->)
1330  *   {
1331  *     static GStaticPrivate current_number_key = G_STATIC_PRIVATE_INIT;
1332  *     int *current_number = g_static_private_get (&amp;current_number_key);
1333  *
1334  *     if (!current_number)
1335  *       {
1336  *         current_number = g_new (int,1);
1337  *         *current_number = 0;
1338  *         g_static_private_set (&amp;current_number_key, current_number, g_free);
1339  *       }
1340  *
1341  *     *current_number = calc_next_number (*current_number);
1342  *
1343  *     return *current_number;
1344  *   }
1345  *  </programlisting>
1346  * </example>
1347  **/
1348
1349 /**
1350  * G_STATIC_PRIVATE_INIT:
1351  *
1352  * Every #GStaticPrivate must be initialized with this macro, before it
1353  * can be used.
1354  *
1355  * <informalexample>
1356  *  <programlisting>
1357  *   GStaticPrivate my_private = G_STATIC_PRIVATE_INIT;
1358  *  </programlisting>
1359  * </informalexample>
1360  **/
1361
1362 /**
1363  * g_static_private_init:
1364  * @private_key: a #GStaticPrivate to be initialized.
1365  *
1366  * Initializes @private_key. Alternatively you can initialize it with
1367  * #G_STATIC_PRIVATE_INIT.
1368  **/
1369 void
1370 g_static_private_init (GStaticPrivate *private_key)
1371 {
1372   private_key->index = 0;
1373 }
1374
1375 /**
1376  * g_static_private_get:
1377  * @private_key: a #GStaticPrivate.
1378  * @Returns: the corresponding pointer.
1379  *
1380  * Works like g_private_get() only for a #GStaticPrivate.
1381  *
1382  * This function works even if g_thread_init() has not yet been called.
1383  **/
1384 gpointer
1385 g_static_private_get (GStaticPrivate *private_key)
1386 {
1387   GRealThread *self = (GRealThread*) g_thread_self ();
1388   GArray *array;
1389   gpointer ret = NULL;
1390
1391   LOCK_PRIVATE_DATA (self);
1392
1393   array = self->private_data;
1394
1395   if (array && private_key->index != 0 && private_key->index <= array->len)
1396     ret = g_array_index (array, GStaticPrivateNode,
1397                          private_key->index - 1).data;
1398
1399   UNLOCK_PRIVATE_DATA (self);
1400   return ret;
1401 }
1402
1403 /**
1404  * g_static_private_set:
1405  * @private_key: a #GStaticPrivate.
1406  * @data: the new pointer.
1407  * @notify: a function to be called with the pointer whenever the
1408  *          current thread ends or sets this pointer again.
1409  *
1410  * Sets the pointer keyed to @private_key for the current thread and
1411  * the function @notify to be called with that pointer (%NULL or
1412  * non-%NULL), whenever the pointer is set again or whenever the
1413  * current thread ends.
1414  *
1415  * This function works even if g_thread_init() has not yet been called.
1416  * If g_thread_init() is called later, the @data keyed to @private_key
1417  * will be inherited only by the main thread, i.e. the one that called
1418  * g_thread_init().
1419  *
1420  * <note><para>@notify is used quite differently from @destructor in
1421  * g_private_new().</para></note>
1422  **/
1423 void
1424 g_static_private_set (GStaticPrivate *private_key,
1425                       gpointer        data,
1426                       GDestroyNotify  notify)
1427 {
1428   GRealThread *self = (GRealThread*) g_thread_self ();
1429   GArray *array;
1430   static guint next_index = 0;
1431   GStaticPrivateNode *node;
1432   gpointer ddata = NULL;
1433   GDestroyNotify ddestroy = NULL;
1434
1435   if (!private_key->index)
1436     {
1437       G_LOCK (g_thread);
1438
1439       if (!private_key->index)
1440         {
1441           if (g_thread_free_indices)
1442             {
1443               private_key->index =
1444                 GPOINTER_TO_UINT (g_thread_free_indices->data);
1445               g_thread_free_indices =
1446                 g_slist_delete_link (g_thread_free_indices,
1447                                      g_thread_free_indices);
1448             }
1449           else
1450             private_key->index = ++next_index;
1451         }
1452
1453       G_UNLOCK (g_thread);
1454     }
1455
1456   LOCK_PRIVATE_DATA (self);
1457
1458   array = self->private_data;
1459   if (!array)
1460     {
1461       array = g_array_new (FALSE, TRUE, sizeof (GStaticPrivateNode));
1462       self->private_data = array;
1463     }
1464
1465   if (private_key->index > array->len)
1466     g_array_set_size (array, private_key->index);
1467
1468   node = &g_array_index (array, GStaticPrivateNode, private_key->index - 1);
1469
1470   ddata = node->data;
1471   ddestroy = node->destroy;
1472
1473   node->data = data;
1474   node->destroy = notify;
1475
1476   UNLOCK_PRIVATE_DATA (self);
1477
1478   if (ddestroy)
1479     ddestroy (ddata);
1480 }
1481
1482 /**
1483  * g_static_private_free:
1484  * @private_key: a #GStaticPrivate to be freed.
1485  *
1486  * Releases all resources allocated to @private_key.
1487  *
1488  * You don't have to call this functions for a #GStaticPrivate with an
1489  * unbounded lifetime, i.e. objects declared 'static', but if you have
1490  * a #GStaticPrivate as a member of a structure and the structure is
1491  * freed, you should also free the #GStaticPrivate.
1492  **/
1493 void
1494 g_static_private_free (GStaticPrivate *private_key)
1495 {
1496   guint idx = private_key->index;
1497   GRealThread *thread, *next;
1498   GArray *garbage = NULL;
1499
1500   if (!idx)
1501     return;
1502
1503   private_key->index = 0;
1504
1505   G_LOCK (g_thread);
1506
1507   thread = g_thread_all_threads;
1508
1509   for (thread = g_thread_all_threads; thread; thread = next)
1510     {
1511       GArray *array;
1512
1513       next = thread->next;
1514
1515       LOCK_PRIVATE_DATA (thread);
1516
1517       array = thread->private_data;
1518
1519       if (array && idx <= array->len)
1520         {
1521           GStaticPrivateNode *node = &g_array_index (array,
1522                                                      GStaticPrivateNode,
1523                                                      idx - 1);
1524           gpointer ddata = node->data;
1525           GDestroyNotify ddestroy = node->destroy;
1526
1527           node->data = NULL;
1528           node->destroy = NULL;
1529
1530           if (ddestroy)
1531             {
1532               /* defer non-trivial destruction til after we've finished
1533                * iterating, since we must continue to hold the lock */
1534               if (garbage == NULL)
1535                 garbage = g_array_new (FALSE, TRUE,
1536                                        sizeof (GStaticPrivateNode));
1537
1538               g_array_set_size (garbage, garbage->len + 1);
1539
1540               node = &g_array_index (garbage, GStaticPrivateNode,
1541                                      garbage->len - 1);
1542               node->data = ddata;
1543               node->destroy = ddestroy;
1544             }
1545         }
1546
1547       UNLOCK_PRIVATE_DATA (thread);
1548     }
1549   g_thread_free_indices = g_slist_prepend (g_thread_free_indices,
1550                                            GUINT_TO_POINTER (idx));
1551   G_UNLOCK (g_thread);
1552
1553   if (garbage)
1554     {
1555       guint i;
1556
1557       for (i = 0; i < garbage->len; i++)
1558         {
1559           GStaticPrivateNode *node;
1560
1561           node = &g_array_index (garbage, GStaticPrivateNode, i);
1562           node->destroy (node->data);
1563         }
1564
1565       g_array_free (garbage, TRUE);
1566     }
1567 }
1568
1569 /* GThread Extra Functions {{{1 ------------------------------------------- */
1570 static void
1571 g_thread_cleanup (gpointer data)
1572 {
1573   if (data)
1574     {
1575       GRealThread* thread = data;
1576       GArray *array;
1577
1578       LOCK_PRIVATE_DATA (thread);
1579       array = thread->private_data;
1580       thread->private_data = NULL;
1581       UNLOCK_PRIVATE_DATA (thread);
1582
1583       if (array)
1584         {
1585           guint i;
1586
1587           for (i = 0; i < array->len; i++ )
1588             {
1589               GStaticPrivateNode *node =
1590                 &g_array_index (array, GStaticPrivateNode, i);
1591               if (node->destroy)
1592                 node->destroy (node->data);
1593             }
1594           g_array_free (array, TRUE);
1595         }
1596
1597       /* We only free the thread structure, if it isn't joinable. If
1598          it is, the structure is freed in g_thread_join */
1599       if (!thread->thread.joinable)
1600         {
1601           GRealThread *t, *p;
1602
1603           G_LOCK (g_thread);
1604           for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1605             {
1606               if (t == thread)
1607                 {
1608                   if (p)
1609                     p->next = t->next;
1610                   else
1611                     g_thread_all_threads = t->next;
1612                   break;
1613                 }
1614             }
1615           G_UNLOCK (g_thread);
1616
1617           /* Just to make sure, this isn't used any more */
1618           g_system_thread_assign (thread->system_thread, zero_thread);
1619           g_free (thread);
1620         }
1621     }
1622 }
1623
1624 static void
1625 g_thread_fail (void)
1626 {
1627   g_error ("The thread system is not yet initialized.");
1628 }
1629
1630 #define G_NSEC_PER_SEC 1000000000
1631
1632 static guint64
1633 gettime (void)
1634 {
1635   return g_get_monotonic_time () * 1000;
1636 }
1637
1638 static gpointer
1639 g_thread_create_proxy (gpointer data)
1640 {
1641   GRealThread* thread = data;
1642
1643   g_assert (data);
1644
1645   /* This has to happen before G_LOCK, as that might call g_thread_self */
1646   g_private_set (&g_thread_specific_private, data);
1647
1648   /* the lock makes sure, that thread->system_thread is written,
1649      before thread->thread.func is called. See g_thread_create. */
1650   G_LOCK (g_thread);
1651   G_UNLOCK (g_thread);
1652
1653   thread->retval = thread->thread.func (thread->thread.data);
1654
1655   return NULL;
1656 }
1657
1658 /**
1659  * g_thread_create:
1660  * @func: a function to execute in the new thread
1661  * @data: an argument to supply to the new thread
1662  * @joinable: should this thread be joinable?
1663  * @error: return location for error, or %NULL
1664  *
1665  * This function creates a new thread.
1666  *
1667  * If @joinable is %TRUE, you can wait for this threads termination
1668  * calling g_thread_join(). Otherwise the thread will just disappear
1669  * when it terminates.
1670  *
1671  * The new thread executes the function @func with the argument @data.
1672  * If the thread was created successfully, it is returned.
1673  *
1674  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1675  * The error is set, if and only if the function returns %NULL.
1676  *
1677  * Returns: the new #GThread on success
1678  */
1679
1680 /**
1681  * g_thread_create_full:
1682  * @func: a function to execute in the new thread.
1683  * @data: an argument to supply to the new thread.
1684  * @stack_size: a stack size for the new thread.
1685  * @joinable: should this thread be joinable?
1686  * @bound: should this thread be bound to a system thread?
1687  * @priority: ignored
1688  * @error: return location for error.
1689  * @Returns: the new #GThread on success.
1690  *
1691  * This function creates a new thread. If the underlying thread
1692  * implementation supports it, the thread gets a stack size of
1693  * @stack_size or the default value for the current platform, if
1694  * @stack_size is 0.
1695  *
1696  * If @joinable is %TRUE, you can wait for this threads termination
1697  * calling g_thread_join(). Otherwise the thread will just disappear
1698  * when it terminates. If @bound is %TRUE, this thread will be
1699  * scheduled in the system scope, otherwise the implementation is free
1700  * to do scheduling in the process scope. The first variant is more
1701  * expensive resource-wise, but generally faster. On some systems (e.g.
1702  * Linux) all threads are bound.
1703  *
1704  * The new thread executes the function @func with the argument @data.
1705  * If the thread was created successfully, it is returned.
1706  *
1707  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
1708  * The error is set, if and only if the function returns %NULL.
1709  *
1710  * <note><para>Only use g_thread_create_full() if you really can't use
1711  * g_thread_create() instead. g_thread_create() does not take
1712  * @stack_size, @bound, and @priority as arguments, as they should only
1713  * be used in cases in which it is unavoidable.</para></note>
1714  **/
1715 GThread*
1716 g_thread_create_full (GThreadFunc       func,
1717                       gpointer          data,
1718                       gulong            stack_size,
1719                       gboolean          joinable,
1720                       gboolean          bound,
1721                       GThreadPriority   priority,
1722                       GError          **error)
1723 {
1724   GRealThread* result;
1725   GError *local_error = NULL;
1726   g_return_val_if_fail (func, NULL);
1727
1728   result = g_new0 (GRealThread, 1);
1729
1730   result->thread.joinable = joinable;
1731   result->thread.func = func;
1732   result->thread.data = data;
1733   result->private_data = NULL;
1734   G_LOCK (g_thread);
1735   g_system_thread_create (g_thread_create_proxy, result,
1736                           stack_size, joinable, bound, 0,
1737                           &result->system_thread, &local_error);
1738   if (!local_error)
1739     {
1740       result->next = g_thread_all_threads;
1741       g_thread_all_threads = result;
1742     }
1743   G_UNLOCK (g_thread);
1744
1745   if (local_error)
1746     {
1747       g_propagate_error (error, local_error);
1748       g_free (result);
1749       return NULL;
1750     }
1751
1752   return (GThread*) result;
1753 }
1754
1755 /**
1756  * g_thread_exit:
1757  * @retval: the return value of this thread.
1758  *
1759  * Exits the current thread. If another thread is waiting for that
1760  * thread using g_thread_join() and the current thread is joinable, the
1761  * waiting thread will be woken up and get @retval as the return value
1762  * of g_thread_join(). If the current thread is not joinable, @retval
1763  * is ignored. Calling
1764  *
1765  * |[
1766  *   g_thread_exit (retval);
1767  * ]|
1768  *
1769  * is equivalent to returning @retval from the function @func, as given
1770  * to g_thread_create().
1771  *
1772  * <note><para>Never call g_thread_exit() from within a thread of a
1773  * #GThreadPool, as that will mess up the bookkeeping and lead to funny
1774  * and unwanted results.</para></note>
1775  **/
1776 void
1777 g_thread_exit (gpointer retval)
1778 {
1779   GRealThread* real = (GRealThread*) g_thread_self ();
1780   real->retval = retval;
1781
1782   g_system_thread_exit ();
1783 }
1784
1785 /**
1786  * g_thread_join:
1787  * @thread: a #GThread to be waited for.
1788  * @Returns: the return value of the thread.
1789  *
1790  * Waits until @thread finishes, i.e. the function @func, as given to
1791  * g_thread_create(), returns or g_thread_exit() is called by @thread.
1792  * All resources of @thread including the #GThread struct are released.
1793  * @thread must have been created with @joinable=%TRUE in
1794  * g_thread_create(). The value returned by @func or given to
1795  * g_thread_exit() by @thread is returned by this function.
1796  **/
1797 gpointer
1798 g_thread_join (GThread* thread)
1799 {
1800   GRealThread* real = (GRealThread*) thread;
1801   GRealThread *p, *t;
1802   gpointer retval;
1803
1804   g_return_val_if_fail (thread, NULL);
1805   g_return_val_if_fail (thread->joinable, NULL);
1806   g_return_val_if_fail (!g_system_thread_equal (&real->system_thread, &zero_thread), NULL);
1807
1808   g_system_thread_join (&real->system_thread);
1809
1810   retval = real->retval;
1811
1812   G_LOCK (g_thread);
1813   for (t = g_thread_all_threads, p = NULL; t; p = t, t = t->next)
1814     {
1815       if (t == (GRealThread*) thread)
1816         {
1817           if (p)
1818             p->next = t->next;
1819           else
1820             g_thread_all_threads = t->next;
1821           break;
1822         }
1823     }
1824   G_UNLOCK (g_thread);
1825
1826   /* Just to make sure, this isn't used any more */
1827   thread->joinable = 0;
1828   g_system_thread_assign (real->system_thread, zero_thread);
1829
1830   /* the thread structure for non-joinable threads is freed upon
1831      thread end. We free the memory here. This will leave a loose end,
1832      if a joinable thread is not joined. */
1833
1834   g_free (thread);
1835
1836   return retval;
1837 }
1838
1839 /**
1840  * g_thread_set_priority:
1841  * @thread: a #GThread.
1842  * @priority: ignored
1843  *
1844  * This function does nothing.
1845  *
1846  * Deprecated:2.32: Thread priorities no longer have any effect.
1847  **/
1848 void
1849 g_thread_set_priority (GThread         *thread,
1850                        GThreadPriority  priority)
1851 {
1852 }
1853
1854 /**
1855  * g_thread_self:
1856  * @Returns: the current thread.
1857  *
1858  * This functions returns the #GThread corresponding to the calling
1859  * thread.
1860  **/
1861 GThread*
1862 g_thread_self (void)
1863 {
1864   GRealThread* thread = g_private_get (&g_thread_specific_private);
1865
1866   if (!thread)
1867     {
1868       /* If no thread data is available, provide and set one.  This
1869          can happen for the main thread and for threads, that are not
1870          created by GLib. */
1871       thread = g_new0 (GRealThread, 1);
1872       thread->thread.joinable = FALSE; /* This is a save guess */
1873       thread->thread.func = NULL;
1874       thread->thread.data = NULL;
1875       thread->private_data = NULL;
1876
1877       g_system_thread_self (&thread->system_thread);
1878
1879       g_private_set (&g_thread_specific_private, thread);
1880
1881       G_LOCK (g_thread);
1882       thread->next = g_thread_all_threads;
1883       g_thread_all_threads = thread;
1884       G_UNLOCK (g_thread);
1885     }
1886
1887   return (GThread*)thread;
1888 }
1889
1890 /* GStaticRWLock {{{1 ----------------------------------------------------- */
1891
1892 /**
1893  * GStaticRWLock:
1894  *
1895  * The #GStaticRWLock struct represents a read-write lock. A read-write
1896  * lock can be used for protecting data that some portions of code only
1897  * read from, while others also write. In such situations it is
1898  * desirable that several readers can read at once, whereas of course
1899  * only one writer may write at a time. Take a look at the following
1900  * example:
1901  *
1902  * <example>
1903  *  <title>An array with access functions</title>
1904  *  <programlisting>
1905  *   GStaticRWLock rwlock = G_STATIC_RW_LOCK_INIT;
1906  *   GPtrArray *array;
1907  *
1908  *   gpointer
1909  *   my_array_get (guint index)
1910  *   {
1911  *     gpointer retval = NULL;
1912  *
1913  *     if (!array)
1914  *       return NULL;
1915  *
1916  *     g_static_rw_lock_reader_lock (&amp;rwlock);
1917  *     if (index &lt; array->len)
1918  *       retval = g_ptr_array_index (array, index);
1919  *     g_static_rw_lock_reader_unlock (&amp;rwlock);
1920  *
1921  *     return retval;
1922  *   }
1923  *
1924  *   void
1925  *   my_array_set (guint index, gpointer data)
1926  *   {
1927  *     g_static_rw_lock_writer_lock (&amp;rwlock);
1928  *
1929  *     if (!array)
1930  *       array = g_ptr_array_new (<!-- -->);
1931  *
1932  *     if (index >= array->len)
1933  *       g_ptr_array_set_size (array, index+1);
1934  *     g_ptr_array_index (array, index) = data;
1935  *
1936  *     g_static_rw_lock_writer_unlock (&amp;rwlock);
1937  *   }
1938  *  </programlisting>
1939  * </example>
1940  *
1941  * This example shows an array which can be accessed by many readers
1942  * (the <function>my_array_get()</function> function) simultaneously,
1943  * whereas the writers (the <function>my_array_set()</function>
1944  * function) will only be allowed once at a time and only if no readers
1945  * currently access the array. This is because of the potentially
1946  * dangerous resizing of the array. Using these functions is fully
1947  * multi-thread safe now.
1948  *
1949  * Most of the time, writers should have precedence over readers. That
1950  * means, for this implementation, that as soon as a writer wants to
1951  * lock the data, no other reader is allowed to lock the data, whereas,
1952  * of course, the readers that already have locked the data are allowed
1953  * to finish their operation. As soon as the last reader unlocks the
1954  * data, the writer will lock it.
1955  *
1956  * Even though #GStaticRWLock is not opaque, it should only be used
1957  * with the following functions.
1958  *
1959  * All of the <function>g_static_rw_lock_*</function> functions can be
1960  * used even if g_thread_init() has not been called. Then they do
1961  * nothing, apart from <function>g_static_rw_lock_*_trylock</function>,
1962  * which does nothing but returning %TRUE.
1963  *
1964  * <note><para>A read-write lock has a higher overhead than a mutex. For
1965  * example, both g_static_rw_lock_reader_lock() and
1966  * g_static_rw_lock_reader_unlock() have to lock and unlock a
1967  * #GStaticMutex, so it takes at least twice the time to lock and unlock
1968  * a #GStaticRWLock that it does to lock and unlock a #GStaticMutex. So
1969  * only data structures that are accessed by multiple readers, and which
1970  * keep the lock for a considerable time justify a #GStaticRWLock. The
1971  * above example most probably would fare better with a
1972  * #GStaticMutex.</para></note>
1973  **/
1974
1975 /**
1976  * G_STATIC_RW_LOCK_INIT:
1977  *
1978  * A #GStaticRWLock must be initialized with this macro before it can
1979  * be used. This macro can used be to initialize a variable, but it
1980  * cannot be assigned to a variable. In that case you have to use
1981  * g_static_rw_lock_init().
1982  *
1983  * <informalexample>
1984  *  <programlisting>
1985  *   GStaticRWLock my_lock = G_STATIC_RW_LOCK_INIT;
1986  *  </programlisting>
1987  * </informalexample>
1988  **/
1989
1990 /**
1991  * g_static_rw_lock_init:
1992  * @lock: a #GStaticRWLock to be initialized.
1993  *
1994  * A #GStaticRWLock must be initialized with this function before it
1995  * can be used. Alternatively you can initialize it with
1996  * #G_STATIC_RW_LOCK_INIT.
1997  **/
1998 void
1999 g_static_rw_lock_init (GStaticRWLock* lock)
2000 {
2001   static const GStaticRWLock init_lock = G_STATIC_RW_LOCK_INIT;
2002
2003   g_return_if_fail (lock);
2004
2005   *lock = init_lock;
2006 }
2007
2008 inline static void
2009 g_static_rw_lock_wait (GCond** cond, GStaticMutex* mutex)
2010 {
2011   if (!*cond)
2012       *cond = g_cond_new ();
2013   g_cond_wait (*cond, g_static_mutex_get_mutex (mutex));
2014 }
2015
2016 inline static void
2017 g_static_rw_lock_signal (GStaticRWLock* lock)
2018 {
2019   if (lock->want_to_write && lock->write_cond)
2020     g_cond_signal (lock->write_cond);
2021   else if (lock->want_to_read && lock->read_cond)
2022     g_cond_broadcast (lock->read_cond);
2023 }
2024
2025 /**
2026  * g_static_rw_lock_reader_lock:
2027  * @lock: a #GStaticRWLock to lock for reading.
2028  *
2029  * Locks @lock for reading. There may be unlimited concurrent locks for
2030  * reading of a #GStaticRWLock at the same time.  If @lock is already
2031  * locked for writing by another thread or if another thread is already
2032  * waiting to lock @lock for writing, this function will block until
2033  * @lock is unlocked by the other writing thread and no other writing
2034  * threads want to lock @lock. This lock has to be unlocked by
2035  * g_static_rw_lock_reader_unlock().
2036  *
2037  * #GStaticRWLock is not recursive. It might seem to be possible to
2038  * recursively lock for reading, but that can result in a deadlock, due
2039  * to writer preference.
2040  **/
2041 void
2042 g_static_rw_lock_reader_lock (GStaticRWLock* lock)
2043 {
2044   g_return_if_fail (lock);
2045
2046   if (!g_threads_got_initialized)
2047     return;
2048
2049   g_static_mutex_lock (&lock->mutex);
2050   lock->want_to_read++;
2051   while (lock->have_writer || lock->want_to_write)
2052     g_static_rw_lock_wait (&lock->read_cond, &lock->mutex);
2053   lock->want_to_read--;
2054   lock->read_counter++;
2055   g_static_mutex_unlock (&lock->mutex);
2056 }
2057
2058 /**
2059  * g_static_rw_lock_reader_trylock:
2060  * @lock: a #GStaticRWLock to lock for reading.
2061  * @Returns: %TRUE, if @lock could be locked for reading.
2062  *
2063  * Tries to lock @lock for reading. If @lock is already locked for
2064  * writing by another thread or if another thread is already waiting to
2065  * lock @lock for writing, immediately returns %FALSE. Otherwise locks
2066  * @lock for reading and returns %TRUE. This lock has to be unlocked by
2067  * g_static_rw_lock_reader_unlock().
2068  **/
2069 gboolean
2070 g_static_rw_lock_reader_trylock (GStaticRWLock* lock)
2071 {
2072   gboolean ret_val = FALSE;
2073
2074   g_return_val_if_fail (lock, FALSE);
2075
2076   if (!g_threads_got_initialized)
2077     return TRUE;
2078
2079   g_static_mutex_lock (&lock->mutex);
2080   if (!lock->have_writer && !lock->want_to_write)
2081     {
2082       lock->read_counter++;
2083       ret_val = TRUE;
2084     }
2085   g_static_mutex_unlock (&lock->mutex);
2086   return ret_val;
2087 }
2088
2089 /**
2090  * g_static_rw_lock_reader_unlock:
2091  * @lock: a #GStaticRWLock to unlock after reading.
2092  *
2093  * Unlocks @lock. If a thread waits to lock @lock for writing and all
2094  * locks for reading have been unlocked, the waiting thread is woken up
2095  * and can lock @lock for writing.
2096  **/
2097 void
2098 g_static_rw_lock_reader_unlock  (GStaticRWLock* lock)
2099 {
2100   g_return_if_fail (lock);
2101
2102   if (!g_threads_got_initialized)
2103     return;
2104
2105   g_static_mutex_lock (&lock->mutex);
2106   lock->read_counter--;
2107   if (lock->read_counter == 0)
2108     g_static_rw_lock_signal (lock);
2109   g_static_mutex_unlock (&lock->mutex);
2110 }
2111
2112 /**
2113  * g_static_rw_lock_writer_lock:
2114  * @lock: a #GStaticRWLock to lock for writing.
2115  *
2116  * Locks @lock for writing. If @lock is already locked for writing or
2117  * reading by other threads, this function will block until @lock is
2118  * completely unlocked and then lock @lock for writing. While this
2119  * functions waits to lock @lock, no other thread can lock @lock for
2120  * reading. When @lock is locked for writing, no other thread can lock
2121  * @lock (neither for reading nor writing). This lock has to be
2122  * unlocked by g_static_rw_lock_writer_unlock().
2123  **/
2124 void
2125 g_static_rw_lock_writer_lock (GStaticRWLock* lock)
2126 {
2127   g_return_if_fail (lock);
2128
2129   if (!g_threads_got_initialized)
2130     return;
2131
2132   g_static_mutex_lock (&lock->mutex);
2133   lock->want_to_write++;
2134   while (lock->have_writer || lock->read_counter)
2135     g_static_rw_lock_wait (&lock->write_cond, &lock->mutex);
2136   lock->want_to_write--;
2137   lock->have_writer = TRUE;
2138   g_static_mutex_unlock (&lock->mutex);
2139 }
2140
2141 /**
2142  * g_static_rw_lock_writer_trylock:
2143  * @lock: a #GStaticRWLock to lock for writing.
2144  * @Returns: %TRUE, if @lock could be locked for writing.
2145  *
2146  * Tries to lock @lock for writing. If @lock is already locked (for
2147  * either reading or writing) by another thread, it immediately returns
2148  * %FALSE. Otherwise it locks @lock for writing and returns %TRUE. This
2149  * lock has to be unlocked by g_static_rw_lock_writer_unlock().
2150  **/
2151 gboolean
2152 g_static_rw_lock_writer_trylock (GStaticRWLock* lock)
2153 {
2154   gboolean ret_val = FALSE;
2155
2156   g_return_val_if_fail (lock, FALSE);
2157
2158   if (!g_threads_got_initialized)
2159     return TRUE;
2160
2161   g_static_mutex_lock (&lock->mutex);
2162   if (!lock->have_writer && !lock->read_counter)
2163     {
2164       lock->have_writer = TRUE;
2165       ret_val = TRUE;
2166     }
2167   g_static_mutex_unlock (&lock->mutex);
2168   return ret_val;
2169 }
2170
2171 /**
2172  * g_static_rw_lock_writer_unlock:
2173  * @lock: a #GStaticRWLock to unlock after writing.
2174  *
2175  * Unlocks @lock. If a thread is waiting to lock @lock for writing and
2176  * all locks for reading have been unlocked, the waiting thread is
2177  * woken up and can lock @lock for writing. If no thread is waiting to
2178  * lock @lock for writing, and some thread or threads are waiting to
2179  * lock @lock for reading, the waiting threads are woken up and can
2180  * lock @lock for reading.
2181  **/
2182 void
2183 g_static_rw_lock_writer_unlock (GStaticRWLock* lock)
2184 {
2185   g_return_if_fail (lock);
2186
2187   if (!g_threads_got_initialized)
2188     return;
2189
2190   g_static_mutex_lock (&lock->mutex);
2191   lock->have_writer = FALSE;
2192   g_static_rw_lock_signal (lock);
2193   g_static_mutex_unlock (&lock->mutex);
2194 }
2195
2196 /**
2197  * g_static_rw_lock_free:
2198  * @lock: a #GStaticRWLock to be freed.
2199  *
2200  * Releases all resources allocated to @lock.
2201  *
2202  * You don't have to call this functions for a #GStaticRWLock with an
2203  * unbounded lifetime, i.e. objects declared 'static', but if you have
2204  * a #GStaticRWLock as a member of a structure, and the structure is
2205  * freed, you should also free the #GStaticRWLock.
2206  **/
2207 void
2208 g_static_rw_lock_free (GStaticRWLock* lock)
2209 {
2210   g_return_if_fail (lock);
2211
2212   if (lock->read_cond)
2213     {
2214       g_cond_free (lock->read_cond);
2215       lock->read_cond = NULL;
2216     }
2217   if (lock->write_cond)
2218     {
2219       g_cond_free (lock->write_cond);
2220       lock->write_cond = NULL;
2221     }
2222   g_static_mutex_free (&lock->mutex);
2223 }
2224
2225 /* Unsorted {{{1 ---------------------------------------------------------- */
2226
2227 /**
2228  * g_thread_foreach
2229  * @thread_func: function to call for all GThread structures
2230  * @user_data:   second argument to @thread_func
2231  *
2232  * Call @thread_func on all existing #GThread structures. Note that
2233  * threads may decide to exit while @thread_func is running, so
2234  * without intimate knowledge about the lifetime of foreign threads,
2235  * @thread_func shouldn't access the GThread* pointer passed in as
2236  * first argument. However, @thread_func will not be called for threads
2237  * which are known to have exited already.
2238  *
2239  * Due to thread lifetime checks, this function has an execution complexity
2240  * which is quadratic in the number of existing threads.
2241  *
2242  * Since: 2.10
2243  */
2244 void
2245 g_thread_foreach (GFunc    thread_func,
2246                   gpointer user_data)
2247 {
2248   GSList *slist = NULL;
2249   GRealThread *thread;
2250   g_return_if_fail (thread_func != NULL);
2251   /* snapshot the list of threads for iteration */
2252   G_LOCK (g_thread);
2253   for (thread = g_thread_all_threads; thread; thread = thread->next)
2254     slist = g_slist_prepend (slist, thread);
2255   G_UNLOCK (g_thread);
2256   /* walk the list, skipping non-existent threads */
2257   while (slist)
2258     {
2259       GSList *node = slist;
2260       slist = node->next;
2261       /* check whether the current thread still exists */
2262       G_LOCK (g_thread);
2263       for (thread = g_thread_all_threads; thread; thread = thread->next)
2264         if (thread == node->data)
2265           break;
2266       G_UNLOCK (g_thread);
2267       if (thread)
2268         thread_func (thread, user_data);
2269       g_slist_free_1 (node);
2270     }
2271 }
2272
2273 /**
2274  * g_thread_get_initialized:
2275  *
2276  * Indicates if g_thread_init() has been called.
2277  *
2278  * Returns: %TRUE if threads have been initialized.
2279  *
2280  * Since: 2.20
2281  */
2282 gboolean
2283 g_thread_get_initialized ()
2284 {
2285   return g_thread_supported ();
2286 }
2287
2288 /**
2289  * g_mutex_new:
2290  *
2291  * Creates a new #GMutex.
2292  *
2293  * Returns: a newly allocated #GMutex. Use g_mutex_free() to free
2294  */
2295 GMutex *
2296 g_mutex_new (void)
2297 {
2298   GMutex *mutex;
2299
2300   mutex = g_slice_new (GMutex);
2301   g_mutex_init (mutex);
2302
2303   return mutex;
2304 }
2305
2306 /**
2307  * g_mutex_free:
2308  * @mutex: a #GMutex
2309  *
2310  * Destroys a @mutex that has been created with g_mutex_new().
2311  *
2312  * <note>Calling g_mutex_free() on a locked mutex may result
2313  * in undefined behaviour.</note>
2314  */
2315 void
2316 g_mutex_free (GMutex *mutex)
2317 {
2318   g_mutex_clear (mutex);
2319   g_slice_free (GMutex, mutex);
2320 }
2321
2322 /**
2323  * g_cond_new:
2324  *
2325  * Creates a new #GCond.
2326  *
2327  * Returns: a newly allocated #GCond. Free with g_cond_free()
2328  */
2329 GCond *
2330 g_cond_new (void)
2331 {
2332   GCond *cond;
2333
2334   cond = g_slice_new (GCond);
2335   g_cond_init (cond);
2336
2337   return cond;
2338 }
2339
2340 /**
2341  * g_cond_free:
2342  * @cond: a #GCond
2343  *
2344  * Destroys a #GCond that has been created with g_cond_new().
2345  */
2346 void
2347 g_cond_free (GCond *cond)
2348 {
2349   g_cond_clear (cond);
2350   g_slice_free (GCond, cond);
2351 }
2352
2353 /**
2354  * g_private_new:
2355  * @destructor: a function to destroy the data keyed to
2356  *     the #GPrivate when a thread ends
2357  *
2358  * Creates a new #GPrivate. If @destructor is non-%NULL, it is a
2359  * pointer to a destructor function. Whenever a thread ends and the
2360  * corresponding pointer keyed to this instance of #GPrivate is
2361  * non-%NULL, the destructor is called with this pointer as the
2362  * argument.
2363  *
2364  * <note><para>
2365  * #GStaticPrivate is a better choice for most uses.
2366  * </para></note>
2367  *
2368  * <note><para>@destructor is used quite differently from @notify in
2369  * g_static_private_set().</para></note>
2370  *
2371  * <note><para>A #GPrivate cannot be freed. Reuse it instead, if you
2372  * can, to avoid shortage, or use #GStaticPrivate.</para></note>
2373  *
2374  * <note><para>This function will abort if g_thread_init() has not been
2375  * called yet.</para></note>
2376  *
2377  * Returns: a newly allocated #GPrivate
2378  */
2379 GPrivate *
2380 g_private_new (GDestroyNotify notify)
2381 {
2382   GPrivate *key;
2383
2384   key = g_slice_new (GPrivate);
2385   g_private_init (key, notify);
2386
2387   return key;
2388 }
2389
2390 GThreadFunctions g_thread_functions_for_glib_use =
2391 {
2392   g_mutex_new,
2393   g_mutex_lock,
2394   g_mutex_trylock,
2395   g_mutex_unlock,
2396   g_mutex_free,
2397   g_cond_new,
2398   g_cond_signal,
2399   g_cond_broadcast,
2400   g_cond_wait,
2401   g_cond_timed_wait,
2402   g_cond_free,
2403   g_private_new,
2404   g_private_get,
2405   g_private_set,
2406   NULL,
2407   g_thread_yield,
2408   NULL,
2409   NULL,
2410   NULL,
2411   NULL,
2412   NULL,
2413 };