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