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