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