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