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