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