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