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