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