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