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