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