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