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