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