Imported Upstream version 2.61.2
[platform/upstream/glib.git] / glib / gthread-posix.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: posix thread system implementation
5  * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 /*
22  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GLib Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GLib at ftp://ftp.gtk.org/pub/gtk/.
26  */
27
28 /* The GMutex, GCond and GPrivate implementations in this file are some
29  * of the lowest-level code in GLib.  All other parts of GLib (messages,
30  * memory, slices, etc) assume that they can freely use these facilities
31  * without risking recursion.
32  *
33  * As such, these functions are NOT permitted to call any other part of
34  * GLib.
35  *
36  * The thread manipulation functions (create, exit, join, etc.) have
37  * more freedom -- they can do as they please.
38  */
39
40 #include "config.h"
41
42 #include "gthread.h"
43
44 #include "gthreadprivate.h"
45 #include "gslice.h"
46 #include "gmessages.h"
47 #include "gstrfuncs.h"
48 #include "gmain.h"
49 #include "gutils.h"
50
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <pthread.h>
56
57 #include <sys/time.h>
58 #include <unistd.h>
59
60 #ifdef HAVE_SCHED_H
61 #include <sched.h>
62 #endif
63 #ifdef G_OS_WIN32
64 #include <windows.h>
65 #endif
66
67 /* clang defines __ATOMIC_SEQ_CST but doesn't support the GCC extension */
68 #if defined(HAVE_FUTEX) && defined(__ATOMIC_SEQ_CST) && !defined(__clang__)
69 #define USE_NATIVE_MUTEX
70 #endif
71
72 static void
73 g_thread_abort (gint         status,
74                 const gchar *function)
75 {
76   fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s.  Aborting.\n",
77            function, strerror (status));
78   g_abort ();
79 }
80
81 /* {{{1 GMutex */
82
83 #if !defined(USE_NATIVE_MUTEX)
84
85 static pthread_mutex_t *
86 g_mutex_impl_new (void)
87 {
88   pthread_mutexattr_t *pattr = NULL;
89   pthread_mutex_t *mutex;
90   gint status;
91 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
92   pthread_mutexattr_t attr;
93 #endif
94
95   mutex = malloc (sizeof (pthread_mutex_t));
96   if G_UNLIKELY (mutex == NULL)
97     g_thread_abort (errno, "malloc");
98
99 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
100   pthread_mutexattr_init (&attr);
101   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
102   pattr = &attr;
103 #endif
104
105   if G_UNLIKELY ((status = pthread_mutex_init (mutex, pattr)) != 0)
106     g_thread_abort (status, "pthread_mutex_init");
107
108 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
109   pthread_mutexattr_destroy (&attr);
110 #endif
111
112   return mutex;
113 }
114
115 static void
116 g_mutex_impl_free (pthread_mutex_t *mutex)
117 {
118   pthread_mutex_destroy (mutex);
119   free (mutex);
120 }
121
122 static inline pthread_mutex_t *
123 g_mutex_get_impl (GMutex *mutex)
124 {
125   pthread_mutex_t *impl = g_atomic_pointer_get (&mutex->p);
126
127   if G_UNLIKELY (impl == NULL)
128     {
129       impl = g_mutex_impl_new ();
130       if (!g_atomic_pointer_compare_and_exchange (&mutex->p, NULL, impl))
131         g_mutex_impl_free (impl);
132       impl = mutex->p;
133     }
134
135   return impl;
136 }
137
138
139 /**
140  * g_mutex_init:
141  * @mutex: an uninitialized #GMutex
142  *
143  * Initializes a #GMutex so that it can be used.
144  *
145  * This function is useful to initialize a mutex that has been
146  * allocated on the stack, or as part of a larger structure.
147  * It is not necessary to initialize a mutex that has been
148  * statically allocated.
149  *
150  * |[<!-- language="C" --> 
151  *   typedef struct {
152  *     GMutex m;
153  *     ...
154  *   } Blob;
155  *
156  * Blob *b;
157  *
158  * b = g_new (Blob, 1);
159  * g_mutex_init (&b->m);
160  * ]|
161  *
162  * To undo the effect of g_mutex_init() when a mutex is no longer
163  * needed, use g_mutex_clear().
164  *
165  * Calling g_mutex_init() on an already initialized #GMutex leads
166  * to undefined behaviour.
167  *
168  * Since: 2.32
169  */
170 void
171 g_mutex_init (GMutex *mutex)
172 {
173   mutex->p = g_mutex_impl_new ();
174 }
175
176 /**
177  * g_mutex_clear:
178  * @mutex: an initialized #GMutex
179  *
180  * Frees the resources allocated to a mutex with g_mutex_init().
181  *
182  * This function should not be used with a #GMutex that has been
183  * statically allocated.
184  *
185  * Calling g_mutex_clear() on a locked mutex leads to undefined
186  * behaviour.
187  *
188  * Sine: 2.32
189  */
190 void
191 g_mutex_clear (GMutex *mutex)
192 {
193   g_mutex_impl_free (mutex->p);
194 }
195
196 /**
197  * g_mutex_lock:
198  * @mutex: a #GMutex
199  *
200  * Locks @mutex. If @mutex is already locked by another thread, the
201  * current thread will block until @mutex is unlocked by the other
202  * thread.
203  *
204  * #GMutex is neither guaranteed to be recursive nor to be
205  * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
206  * already been locked by the same thread results in undefined behaviour
207  * (including but not limited to deadlocks).
208  */
209 void
210 g_mutex_lock (GMutex *mutex)
211 {
212   gint status;
213
214   if G_UNLIKELY ((status = pthread_mutex_lock (g_mutex_get_impl (mutex))) != 0)
215     g_thread_abort (status, "pthread_mutex_lock");
216 }
217
218 /**
219  * g_mutex_unlock:
220  * @mutex: a #GMutex
221  *
222  * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
223  * call for @mutex, it will become unblocked and can lock @mutex itself.
224  *
225  * Calling g_mutex_unlock() on a mutex that is not locked by the
226  * current thread leads to undefined behaviour.
227  */
228 void
229 g_mutex_unlock (GMutex *mutex)
230 {
231   gint status;
232
233   if G_UNLIKELY ((status = pthread_mutex_unlock (g_mutex_get_impl (mutex))) != 0)
234     g_thread_abort (status, "pthread_mutex_unlock");
235 }
236
237 /**
238  * g_mutex_trylock:
239  * @mutex: a #GMutex
240  *
241  * Tries to lock @mutex. If @mutex is already locked by another thread,
242  * it immediately returns %FALSE. Otherwise it locks @mutex and returns
243  * %TRUE.
244  *
245  * #GMutex is neither guaranteed to be recursive nor to be
246  * non-recursive.  As such, calling g_mutex_lock() on a #GMutex that has
247  * already been locked by the same thread results in undefined behaviour
248  * (including but not limited to deadlocks or arbitrary return values).
249  *
250  * Returns: %TRUE if @mutex could be locked
251  */
252 gboolean
253 g_mutex_trylock (GMutex *mutex)
254 {
255   gint status;
256
257   if G_LIKELY ((status = pthread_mutex_trylock (g_mutex_get_impl (mutex))) == 0)
258     return TRUE;
259
260   if G_UNLIKELY (status != EBUSY)
261     g_thread_abort (status, "pthread_mutex_trylock");
262
263   return FALSE;
264 }
265
266 #endif /* !defined(USE_NATIVE_MUTEX) */
267
268 /* {{{1 GRecMutex */
269
270 static pthread_mutex_t *
271 g_rec_mutex_impl_new (void)
272 {
273   pthread_mutexattr_t attr;
274   pthread_mutex_t *mutex;
275
276   mutex = malloc (sizeof (pthread_mutex_t));
277   if G_UNLIKELY (mutex == NULL)
278     g_thread_abort (errno, "malloc");
279
280   pthread_mutexattr_init (&attr);
281   pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
282   pthread_mutex_init (mutex, &attr);
283   pthread_mutexattr_destroy (&attr);
284
285   return mutex;
286 }
287
288 static void
289 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
290 {
291   pthread_mutex_destroy (mutex);
292   free (mutex);
293 }
294
295 static inline pthread_mutex_t *
296 g_rec_mutex_get_impl (GRecMutex *rec_mutex)
297 {
298   pthread_mutex_t *impl = g_atomic_pointer_get (&rec_mutex->p);
299
300   if G_UNLIKELY (impl == NULL)
301     {
302       impl = g_rec_mutex_impl_new ();
303       if (!g_atomic_pointer_compare_and_exchange (&rec_mutex->p, NULL, impl))
304         g_rec_mutex_impl_free (impl);
305       impl = rec_mutex->p;
306     }
307
308   return impl;
309 }
310
311 /**
312  * g_rec_mutex_init:
313  * @rec_mutex: an uninitialized #GRecMutex
314  *
315  * Initializes a #GRecMutex so that it can be used.
316  *
317  * This function is useful to initialize a recursive mutex
318  * that has been allocated on the stack, or as part of a larger
319  * structure.
320  *
321  * It is not necessary to initialise a recursive mutex that has been
322  * statically allocated.
323  *
324  * |[<!-- language="C" --> 
325  *   typedef struct {
326  *     GRecMutex m;
327  *     ...
328  *   } Blob;
329  *
330  * Blob *b;
331  *
332  * b = g_new (Blob, 1);
333  * g_rec_mutex_init (&b->m);
334  * ]|
335  *
336  * Calling g_rec_mutex_init() on an already initialized #GRecMutex
337  * leads to undefined behaviour.
338  *
339  * To undo the effect of g_rec_mutex_init() when a recursive mutex
340  * is no longer needed, use g_rec_mutex_clear().
341  *
342  * Since: 2.32
343  */
344 void
345 g_rec_mutex_init (GRecMutex *rec_mutex)
346 {
347   rec_mutex->p = g_rec_mutex_impl_new ();
348 }
349
350 /**
351  * g_rec_mutex_clear:
352  * @rec_mutex: an initialized #GRecMutex
353  *
354  * Frees the resources allocated to a recursive mutex with
355  * g_rec_mutex_init().
356  *
357  * This function should not be used with a #GRecMutex that has been
358  * statically allocated.
359  *
360  * Calling g_rec_mutex_clear() on a locked recursive mutex leads
361  * to undefined behaviour.
362  *
363  * Sine: 2.32
364  */
365 void
366 g_rec_mutex_clear (GRecMutex *rec_mutex)
367 {
368   g_rec_mutex_impl_free (rec_mutex->p);
369 }
370
371 /**
372  * g_rec_mutex_lock:
373  * @rec_mutex: a #GRecMutex
374  *
375  * Locks @rec_mutex. If @rec_mutex is already locked by another
376  * thread, the current thread will block until @rec_mutex is
377  * unlocked by the other thread. If @rec_mutex is already locked
378  * by the current thread, the 'lock count' of @rec_mutex is increased.
379  * The mutex will only become available again when it is unlocked
380  * as many times as it has been locked.
381  *
382  * Since: 2.32
383  */
384 void
385 g_rec_mutex_lock (GRecMutex *mutex)
386 {
387   pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
388 }
389
390 /**
391  * g_rec_mutex_unlock:
392  * @rec_mutex: a #GRecMutex
393  *
394  * Unlocks @rec_mutex. If another thread is blocked in a
395  * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
396  * and can lock @rec_mutex itself.
397  *
398  * Calling g_rec_mutex_unlock() on a recursive mutex that is not
399  * locked by the current thread leads to undefined behaviour.
400  *
401  * Since: 2.32
402  */
403 void
404 g_rec_mutex_unlock (GRecMutex *rec_mutex)
405 {
406   pthread_mutex_unlock (rec_mutex->p);
407 }
408
409 /**
410  * g_rec_mutex_trylock:
411  * @rec_mutex: a #GRecMutex
412  *
413  * Tries to lock @rec_mutex. If @rec_mutex is already locked
414  * by another thread, it immediately returns %FALSE. Otherwise
415  * it locks @rec_mutex and returns %TRUE.
416  *
417  * Returns: %TRUE if @rec_mutex could be locked
418  *
419  * Since: 2.32
420  */
421 gboolean
422 g_rec_mutex_trylock (GRecMutex *rec_mutex)
423 {
424   if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
425     return FALSE;
426
427   return TRUE;
428 }
429
430 /* {{{1 GRWLock */
431
432 static pthread_rwlock_t *
433 g_rw_lock_impl_new (void)
434 {
435   pthread_rwlock_t *rwlock;
436   gint status;
437
438   rwlock = malloc (sizeof (pthread_rwlock_t));
439   if G_UNLIKELY (rwlock == NULL)
440     g_thread_abort (errno, "malloc");
441
442   if G_UNLIKELY ((status = pthread_rwlock_init (rwlock, NULL)) != 0)
443     g_thread_abort (status, "pthread_rwlock_init");
444
445   return rwlock;
446 }
447
448 static void
449 g_rw_lock_impl_free (pthread_rwlock_t *rwlock)
450 {
451   pthread_rwlock_destroy (rwlock);
452   free (rwlock);
453 }
454
455 static inline pthread_rwlock_t *
456 g_rw_lock_get_impl (GRWLock *lock)
457 {
458   pthread_rwlock_t *impl = g_atomic_pointer_get (&lock->p);
459
460   if G_UNLIKELY (impl == NULL)
461     {
462       impl = g_rw_lock_impl_new ();
463       if (!g_atomic_pointer_compare_and_exchange (&lock->p, NULL, impl))
464         g_rw_lock_impl_free (impl);
465       impl = lock->p;
466     }
467
468   return impl;
469 }
470
471 /**
472  * g_rw_lock_init:
473  * @rw_lock: an uninitialized #GRWLock
474  *
475  * Initializes a #GRWLock so that it can be used.
476  *
477  * This function is useful to initialize a lock that has been
478  * allocated on the stack, or as part of a larger structure.  It is not
479  * necessary to initialise a reader-writer lock that has been statically
480  * allocated.
481  *
482  * |[<!-- language="C" --> 
483  *   typedef struct {
484  *     GRWLock l;
485  *     ...
486  *   } Blob;
487  *
488  * Blob *b;
489  *
490  * b = g_new (Blob, 1);
491  * g_rw_lock_init (&b->l);
492  * ]|
493  *
494  * To undo the effect of g_rw_lock_init() when a lock is no longer
495  * needed, use g_rw_lock_clear().
496  *
497  * Calling g_rw_lock_init() on an already initialized #GRWLock leads
498  * to undefined behaviour.
499  *
500  * Since: 2.32
501  */
502 void
503 g_rw_lock_init (GRWLock *rw_lock)
504 {
505   rw_lock->p = g_rw_lock_impl_new ();
506 }
507
508 /**
509  * g_rw_lock_clear:
510  * @rw_lock: an initialized #GRWLock
511  *
512  * Frees the resources allocated to a lock with g_rw_lock_init().
513  *
514  * This function should not be used with a #GRWLock that has been
515  * statically allocated.
516  *
517  * Calling g_rw_lock_clear() when any thread holds the lock
518  * leads to undefined behaviour.
519  *
520  * Sine: 2.32
521  */
522 void
523 g_rw_lock_clear (GRWLock *rw_lock)
524 {
525   g_rw_lock_impl_free (rw_lock->p);
526 }
527
528 /**
529  * g_rw_lock_writer_lock:
530  * @rw_lock: a #GRWLock
531  *
532  * Obtain a write lock on @rw_lock. If any thread already holds
533  * a read or write lock on @rw_lock, the current thread will block
534  * until all other threads have dropped their locks on @rw_lock.
535  *
536  * Since: 2.32
537  */
538 void
539 g_rw_lock_writer_lock (GRWLock *rw_lock)
540 {
541   int retval = pthread_rwlock_wrlock (g_rw_lock_get_impl (rw_lock));
542
543   if (retval != 0)
544     g_critical ("Failed to get RW lock %p: %s", rw_lock, g_strerror (retval));
545 }
546
547 /**
548  * g_rw_lock_writer_trylock:
549  * @rw_lock: a #GRWLock
550  *
551  * Tries to obtain a write lock on @rw_lock. If any other thread holds
552  * a read or write lock on @rw_lock, it immediately returns %FALSE.
553  * Otherwise it locks @rw_lock and returns %TRUE.
554  *
555  * Returns: %TRUE if @rw_lock could be locked
556  *
557  * Since: 2.32
558  */
559 gboolean
560 g_rw_lock_writer_trylock (GRWLock *rw_lock)
561 {
562   if (pthread_rwlock_trywrlock (g_rw_lock_get_impl (rw_lock)) != 0)
563     return FALSE;
564
565   return TRUE;
566 }
567
568 /**
569  * g_rw_lock_writer_unlock:
570  * @rw_lock: a #GRWLock
571  *
572  * Release a write lock on @rw_lock.
573  *
574  * Calling g_rw_lock_writer_unlock() on a lock that is not held
575  * by the current thread leads to undefined behaviour.
576  *
577  * Since: 2.32
578  */
579 void
580 g_rw_lock_writer_unlock (GRWLock *rw_lock)
581 {
582   pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
583 }
584
585 /**
586  * g_rw_lock_reader_lock:
587  * @rw_lock: a #GRWLock
588  *
589  * Obtain a read lock on @rw_lock. If another thread currently holds
590  * the write lock on @rw_lock, the current thread will block. If another thread
591  * does not hold the write lock, but is waiting for it, it is implementation
592  * defined whether the reader or writer will block. Read locks can be taken
593  * recursively.
594  *
595  * It is implementation-defined how many threads are allowed to
596  * hold read locks on the same lock simultaneously. If the limit is hit,
597  * or if a deadlock is detected, a critical warning will be emitted.
598  *
599  * Since: 2.32
600  */
601 void
602 g_rw_lock_reader_lock (GRWLock *rw_lock)
603 {
604   int retval = pthread_rwlock_rdlock (g_rw_lock_get_impl (rw_lock));
605
606   if (retval != 0)
607     g_critical ("Failed to get RW lock %p: %s", rw_lock, g_strerror (retval));
608 }
609
610 /**
611  * g_rw_lock_reader_trylock:
612  * @rw_lock: a #GRWLock
613  *
614  * Tries to obtain a read lock on @rw_lock and returns %TRUE if
615  * the read lock was successfully obtained. Otherwise it
616  * returns %FALSE.
617  *
618  * Returns: %TRUE if @rw_lock could be locked
619  *
620  * Since: 2.32
621  */
622 gboolean
623 g_rw_lock_reader_trylock (GRWLock *rw_lock)
624 {
625   if (pthread_rwlock_tryrdlock (g_rw_lock_get_impl (rw_lock)) != 0)
626     return FALSE;
627
628   return TRUE;
629 }
630
631 /**
632  * g_rw_lock_reader_unlock:
633  * @rw_lock: a #GRWLock
634  *
635  * Release a read lock on @rw_lock.
636  *
637  * Calling g_rw_lock_reader_unlock() on a lock that is not held
638  * by the current thread leads to undefined behaviour.
639  *
640  * Since: 2.32
641  */
642 void
643 g_rw_lock_reader_unlock (GRWLock *rw_lock)
644 {
645   pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
646 }
647
648 /* {{{1 GCond */
649
650 #if !defined(USE_NATIVE_MUTEX)
651
652 static pthread_cond_t *
653 g_cond_impl_new (void)
654 {
655   pthread_condattr_t attr;
656   pthread_cond_t *cond;
657   gint status;
658
659   pthread_condattr_init (&attr);
660
661 #ifdef HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP
662 #elif defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
663   if G_UNLIKELY ((status = pthread_condattr_setclock (&attr, CLOCK_MONOTONIC)) != 0)
664     g_thread_abort (status, "pthread_condattr_setclock");
665 #else
666 #error Cannot support GCond on your platform.
667 #endif
668
669   cond = malloc (sizeof (pthread_cond_t));
670   if G_UNLIKELY (cond == NULL)
671     g_thread_abort (errno, "malloc");
672
673   if G_UNLIKELY ((status = pthread_cond_init (cond, &attr)) != 0)
674     g_thread_abort (status, "pthread_cond_init");
675
676   pthread_condattr_destroy (&attr);
677
678   return cond;
679 }
680
681 static void
682 g_cond_impl_free (pthread_cond_t *cond)
683 {
684   pthread_cond_destroy (cond);
685   free (cond);
686 }
687
688 static inline pthread_cond_t *
689 g_cond_get_impl (GCond *cond)
690 {
691   pthread_cond_t *impl = g_atomic_pointer_get (&cond->p);
692
693   if G_UNLIKELY (impl == NULL)
694     {
695       impl = g_cond_impl_new ();
696       if (!g_atomic_pointer_compare_and_exchange (&cond->p, NULL, impl))
697         g_cond_impl_free (impl);
698       impl = cond->p;
699     }
700
701   return impl;
702 }
703
704 /**
705  * g_cond_init:
706  * @cond: an uninitialized #GCond
707  *
708  * Initialises a #GCond so that it can be used.
709  *
710  * This function is useful to initialise a #GCond that has been
711  * allocated as part of a larger structure.  It is not necessary to
712  * initialise a #GCond that has been statically allocated.
713  *
714  * To undo the effect of g_cond_init() when a #GCond is no longer
715  * needed, use g_cond_clear().
716  *
717  * Calling g_cond_init() on an already-initialised #GCond leads
718  * to undefined behaviour.
719  *
720  * Since: 2.32
721  */
722 void
723 g_cond_init (GCond *cond)
724 {
725   cond->p = g_cond_impl_new ();
726 }
727
728 /**
729  * g_cond_clear:
730  * @cond: an initialised #GCond
731  *
732  * Frees the resources allocated to a #GCond with g_cond_init().
733  *
734  * This function should not be used with a #GCond that has been
735  * statically allocated.
736  *
737  * Calling g_cond_clear() for a #GCond on which threads are
738  * blocking leads to undefined behaviour.
739  *
740  * Since: 2.32
741  */
742 void
743 g_cond_clear (GCond *cond)
744 {
745   g_cond_impl_free (cond->p);
746 }
747
748 /**
749  * g_cond_wait:
750  * @cond: a #GCond
751  * @mutex: a #GMutex that is currently locked
752  *
753  * Atomically releases @mutex and waits until @cond is signalled.
754  * When this function returns, @mutex is locked again and owned by the
755  * calling thread.
756  *
757  * When using condition variables, it is possible that a spurious wakeup
758  * may occur (ie: g_cond_wait() returns even though g_cond_signal() was
759  * not called).  It's also possible that a stolen wakeup may occur.
760  * This is when g_cond_signal() is called, but another thread acquires
761  * @mutex before this thread and modifies the state of the program in
762  * such a way that when g_cond_wait() is able to return, the expected
763  * condition is no longer met.
764  *
765  * For this reason, g_cond_wait() must always be used in a loop.  See
766  * the documentation for #GCond for a complete example.
767  **/
768 void
769 g_cond_wait (GCond  *cond,
770              GMutex *mutex)
771 {
772   gint status;
773
774   if G_UNLIKELY ((status = pthread_cond_wait (g_cond_get_impl (cond), g_mutex_get_impl (mutex))) != 0)
775     g_thread_abort (status, "pthread_cond_wait");
776 }
777
778 /**
779  * g_cond_signal:
780  * @cond: a #GCond
781  *
782  * If threads are waiting for @cond, at least one of them is unblocked.
783  * If no threads are waiting for @cond, this function has no effect.
784  * It is good practice to hold the same lock as the waiting thread
785  * while calling this function, though not required.
786  */
787 void
788 g_cond_signal (GCond *cond)
789 {
790   gint status;
791
792   if G_UNLIKELY ((status = pthread_cond_signal (g_cond_get_impl (cond))) != 0)
793     g_thread_abort (status, "pthread_cond_signal");
794 }
795
796 /**
797  * g_cond_broadcast:
798  * @cond: a #GCond
799  *
800  * If threads are waiting for @cond, all of them are unblocked.
801  * If no threads are waiting for @cond, this function has no effect.
802  * It is good practice to lock the same mutex as the waiting threads
803  * while calling this function, though not required.
804  */
805 void
806 g_cond_broadcast (GCond *cond)
807 {
808   gint status;
809
810   if G_UNLIKELY ((status = pthread_cond_broadcast (g_cond_get_impl (cond))) != 0)
811     g_thread_abort (status, "pthread_cond_broadcast");
812 }
813
814 /**
815  * g_cond_wait_until:
816  * @cond: a #GCond
817  * @mutex: a #GMutex that is currently locked
818  * @end_time: the monotonic time to wait until
819  *
820  * Waits until either @cond is signalled or @end_time has passed.
821  *
822  * As with g_cond_wait() it is possible that a spurious or stolen wakeup
823  * could occur.  For that reason, waiting on a condition variable should
824  * always be in a loop, based on an explicitly-checked predicate.
825  *
826  * %TRUE is returned if the condition variable was signalled (or in the
827  * case of a spurious wakeup).  %FALSE is returned if @end_time has
828  * passed.
829  *
830  * The following code shows how to correctly perform a timed wait on a
831  * condition variable (extending the example presented in the
832  * documentation for #GCond):
833  *
834  * |[<!-- language="C" --> 
835  * gpointer
836  * pop_data_timed (void)
837  * {
838  *   gint64 end_time;
839  *   gpointer data;
840  *
841  *   g_mutex_lock (&data_mutex);
842  *
843  *   end_time = g_get_monotonic_time () + 5 * G_TIME_SPAN_SECOND;
844  *   while (!current_data)
845  *     if (!g_cond_wait_until (&data_cond, &data_mutex, end_time))
846  *       {
847  *         // timeout has passed.
848  *         g_mutex_unlock (&data_mutex);
849  *         return NULL;
850  *       }
851  *
852  *   // there is data for us
853  *   data = current_data;
854  *   current_data = NULL;
855  *
856  *   g_mutex_unlock (&data_mutex);
857  *
858  *   return data;
859  * }
860  * ]|
861  *
862  * Notice that the end time is calculated once, before entering the
863  * loop and reused.  This is the motivation behind the use of absolute
864  * time on this API -- if a relative time of 5 seconds were passed
865  * directly to the call and a spurious wakeup occurred, the program would
866  * have to start over waiting again (which would lead to a total wait
867  * time of more than 5 seconds).
868  *
869  * Returns: %TRUE on a signal, %FALSE on a timeout
870  * Since: 2.32
871  **/
872 gboolean
873 g_cond_wait_until (GCond  *cond,
874                    GMutex *mutex,
875                    gint64  end_time)
876 {
877   struct timespec ts;
878   gint status;
879
880 #ifdef HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP
881   /* end_time is given relative to the monotonic clock as returned by
882    * g_get_monotonic_time().
883    *
884    * Since this pthreads wants the relative time, convert it back again.
885    */
886   {
887     gint64 now = g_get_monotonic_time ();
888     gint64 relative;
889
890     if (end_time <= now)
891       return FALSE;
892
893     relative = end_time - now;
894
895     ts.tv_sec = relative / 1000000;
896     ts.tv_nsec = (relative % 1000000) * 1000;
897
898     if ((status = pthread_cond_timedwait_relative_np (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &ts)) == 0)
899       return TRUE;
900   }
901 #elif defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
902   /* This is the exact check we used during init to set the clock to
903    * monotonic, so if we're in this branch, timedwait() will already be
904    * expecting a monotonic clock.
905    */
906   {
907     ts.tv_sec = end_time / 1000000;
908     ts.tv_nsec = (end_time % 1000000) * 1000;
909
910     if ((status = pthread_cond_timedwait (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &ts)) == 0)
911       return TRUE;
912   }
913 #else
914 #error Cannot support GCond on your platform.
915 #endif
916
917   if G_UNLIKELY (status != ETIMEDOUT)
918     g_thread_abort (status, "pthread_cond_timedwait");
919
920   return FALSE;
921 }
922
923 #endif /* defined(USE_NATIVE_MUTEX) */
924
925 /* {{{1 GPrivate */
926
927 /**
928  * GPrivate:
929  *
930  * The #GPrivate struct is an opaque data structure to represent a
931  * thread-local data key. It is approximately equivalent to the
932  * pthread_setspecific()/pthread_getspecific() APIs on POSIX and to
933  * TlsSetValue()/TlsGetValue() on Windows.
934  *
935  * If you don't already know why you might want this functionality,
936  * then you probably don't need it.
937  *
938  * #GPrivate is a very limited resource (as far as 128 per program,
939  * shared between all libraries). It is also not possible to destroy a
940  * #GPrivate after it has been used. As such, it is only ever acceptable
941  * to use #GPrivate in static scope, and even then sparingly so.
942  *
943  * See G_PRIVATE_INIT() for a couple of examples.
944  *
945  * The #GPrivate structure should be considered opaque.  It should only
946  * be accessed via the g_private_ functions.
947  */
948
949 /**
950  * G_PRIVATE_INIT:
951  * @notify: a #GDestroyNotify
952  *
953  * A macro to assist with the static initialisation of a #GPrivate.
954  *
955  * This macro is useful for the case that a #GDestroyNotify function
956  * should be associated with the key.  This is needed when the key will be
957  * used to point at memory that should be deallocated when the thread
958  * exits.
959  *
960  * Additionally, the #GDestroyNotify will also be called on the previous
961  * value stored in the key when g_private_replace() is used.
962  *
963  * If no #GDestroyNotify is needed, then use of this macro is not
964  * required -- if the #GPrivate is declared in static scope then it will
965  * be properly initialised by default (ie: to all zeros).  See the
966  * examples below.
967  *
968  * |[<!-- language="C" --> 
969  * static GPrivate name_key = G_PRIVATE_INIT (g_free);
970  *
971  * // return value should not be freed
972  * const gchar *
973  * get_local_name (void)
974  * {
975  *   return g_private_get (&name_key);
976  * }
977  *
978  * void
979  * set_local_name (const gchar *name)
980  * {
981  *   g_private_replace (&name_key, g_strdup (name));
982  * }
983  *
984  *
985  * static GPrivate count_key;   // no free function
986  *
987  * gint
988  * get_local_count (void)
989  * {
990  *   return GPOINTER_TO_INT (g_private_get (&count_key));
991  * }
992  *
993  * void
994  * set_local_count (gint count)
995  * {
996  *   g_private_set (&count_key, GINT_TO_POINTER (count));
997  * }
998  * ]|
999  *
1000  * Since: 2.32
1001  **/
1002
1003 static pthread_key_t *
1004 g_private_impl_new (GDestroyNotify notify)
1005 {
1006   pthread_key_t *key;
1007   gint status;
1008
1009   key = malloc (sizeof (pthread_key_t));
1010   if G_UNLIKELY (key == NULL)
1011     g_thread_abort (errno, "malloc");
1012   status = pthread_key_create (key, notify);
1013   if G_UNLIKELY (status != 0)
1014     g_thread_abort (status, "pthread_key_create");
1015
1016   return key;
1017 }
1018
1019 static void
1020 g_private_impl_free (pthread_key_t *key)
1021 {
1022   gint status;
1023
1024   status = pthread_key_delete (*key);
1025   if G_UNLIKELY (status != 0)
1026     g_thread_abort (status, "pthread_key_delete");
1027   free (key);
1028 }
1029
1030 static inline pthread_key_t *
1031 g_private_get_impl (GPrivate *key)
1032 {
1033   pthread_key_t *impl = g_atomic_pointer_get (&key->p);
1034
1035   if G_UNLIKELY (impl == NULL)
1036     {
1037       impl = g_private_impl_new (key->notify);
1038       if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
1039         {
1040           g_private_impl_free (impl);
1041           impl = key->p;
1042         }
1043     }
1044
1045   return impl;
1046 }
1047
1048 /**
1049  * g_private_get:
1050  * @key: a #GPrivate
1051  *
1052  * Returns the current value of the thread local variable @key.
1053  *
1054  * If the value has not yet been set in this thread, %NULL is returned.
1055  * Values are never copied between threads (when a new thread is
1056  * created, for example).
1057  *
1058  * Returns: the thread-local value
1059  */
1060 gpointer
1061 g_private_get (GPrivate *key)
1062 {
1063   /* quote POSIX: No errors are returned from pthread_getspecific(). */
1064   return pthread_getspecific (*g_private_get_impl (key));
1065 }
1066
1067 /**
1068  * g_private_set:
1069  * @key: a #GPrivate
1070  * @value: the new value
1071  *
1072  * Sets the thread local variable @key to have the value @value in the
1073  * current thread.
1074  *
1075  * This function differs from g_private_replace() in the following way:
1076  * the #GDestroyNotify for @key is not called on the old value.
1077  */
1078 void
1079 g_private_set (GPrivate *key,
1080                gpointer  value)
1081 {
1082   gint status;
1083
1084   if G_UNLIKELY ((status = pthread_setspecific (*g_private_get_impl (key), value)) != 0)
1085     g_thread_abort (status, "pthread_setspecific");
1086 }
1087
1088 /**
1089  * g_private_replace:
1090  * @key: a #GPrivate
1091  * @value: the new value
1092  *
1093  * Sets the thread local variable @key to have the value @value in the
1094  * current thread.
1095  *
1096  * This function differs from g_private_set() in the following way: if
1097  * the previous value was non-%NULL then the #GDestroyNotify handler for
1098  * @key is run on it.
1099  *
1100  * Since: 2.32
1101  **/
1102 void
1103 g_private_replace (GPrivate *key,
1104                    gpointer  value)
1105 {
1106   pthread_key_t *impl = g_private_get_impl (key);
1107   gpointer old;
1108   gint status;
1109
1110   old = pthread_getspecific (*impl);
1111   if (old && key->notify)
1112     key->notify (old);
1113
1114   if G_UNLIKELY ((status = pthread_setspecific (*impl, value)) != 0)
1115     g_thread_abort (status, "pthread_setspecific");
1116 }
1117
1118 /* {{{1 GThread */
1119
1120 #define posix_check_err(err, name) G_STMT_START{                        \
1121   int error = (err);                                                    \
1122   if (error)                                                            \
1123     g_error ("file %s: line %d (%s): error '%s' during '%s'",           \
1124            __FILE__, __LINE__, G_STRFUNC,                               \
1125            g_strerror (error), name);                                   \
1126   }G_STMT_END
1127
1128 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
1129
1130 typedef struct
1131 {
1132   GRealThread thread;
1133
1134   pthread_t system_thread;
1135   gboolean  joined;
1136   GMutex    lock;
1137 } GThreadPosix;
1138
1139 void
1140 g_system_thread_free (GRealThread *thread)
1141 {
1142   GThreadPosix *pt = (GThreadPosix *) thread;
1143
1144   if (!pt->joined)
1145     pthread_detach (pt->system_thread);
1146
1147   g_mutex_clear (&pt->lock);
1148
1149   g_slice_free (GThreadPosix, pt);
1150 }
1151
1152 GRealThread *
1153 g_system_thread_new (GThreadFunc   proxy,
1154                      gulong        stack_size,
1155                      const char   *name,
1156                      GThreadFunc   func,
1157                      gpointer      data,
1158                      GError      **error)
1159 {
1160   GThreadPosix *thread;
1161   GRealThread *base_thread;
1162   pthread_attr_t attr;
1163   gint ret;
1164
1165   thread = g_slice_new0 (GThreadPosix);
1166   base_thread = (GRealThread*)thread;
1167   base_thread->ref_count = 2;
1168   base_thread->ours = TRUE;
1169   base_thread->thread.joinable = TRUE;
1170   base_thread->thread.func = func;
1171   base_thread->thread.data = data;
1172   base_thread->name = g_strdup (name);
1173
1174   posix_check_cmd (pthread_attr_init (&attr));
1175
1176 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1177   if (stack_size)
1178     {
1179 #ifdef _SC_THREAD_STACK_MIN
1180       long min_stack_size = sysconf (_SC_THREAD_STACK_MIN);
1181       if (min_stack_size >= 0)
1182         stack_size = MAX ((gulong) min_stack_size, stack_size);
1183 #endif /* _SC_THREAD_STACK_MIN */
1184       /* No error check here, because some systems can't do it and
1185        * we simply don't want threads to fail because of that. */
1186       pthread_attr_setstacksize (&attr, stack_size);
1187     }
1188 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
1189
1190   ret = pthread_create (&thread->system_thread, &attr, (void* (*)(void*))proxy, thread);
1191
1192   posix_check_cmd (pthread_attr_destroy (&attr));
1193
1194   if (ret == EAGAIN)
1195     {
1196       g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN, 
1197                    "Error creating thread: %s", g_strerror (ret));
1198       g_slice_free (GThreadPosix, thread);
1199       return NULL;
1200     }
1201
1202   posix_check_err (ret, "pthread_create");
1203
1204   g_mutex_init (&thread->lock);
1205
1206   return (GRealThread *) thread;
1207 }
1208
1209 /**
1210  * g_thread_yield:
1211  *
1212  * Causes the calling thread to voluntarily relinquish the CPU, so
1213  * that other threads can run.
1214  *
1215  * This function is often used as a method to make busy wait less evil.
1216  */
1217 void
1218 g_thread_yield (void)
1219 {
1220   sched_yield ();
1221 }
1222
1223 void
1224 g_system_thread_wait (GRealThread *thread)
1225 {
1226   GThreadPosix *pt = (GThreadPosix *) thread;
1227
1228   g_mutex_lock (&pt->lock);
1229
1230   if (!pt->joined)
1231     {
1232       posix_check_cmd (pthread_join (pt->system_thread, NULL));
1233       pt->joined = TRUE;
1234     }
1235
1236   g_mutex_unlock (&pt->lock);
1237 }
1238
1239 void
1240 g_system_thread_exit (void)
1241 {
1242   pthread_exit (NULL);
1243 }
1244
1245 void
1246 g_system_thread_set_name (const gchar *name)
1247 {
1248 #if defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID)
1249   pthread_setname_np (pthread_self(), name); /* on Linux and Solaris */
1250 #elif defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID)
1251   pthread_setname_np (name); /* on OS X and iOS */
1252 #endif
1253 }
1254
1255 /* {{{1 GMutex and GCond futex implementation */
1256
1257 #if defined(USE_NATIVE_MUTEX)
1258
1259 #include <linux/futex.h>
1260 #include <sys/syscall.h>
1261
1262 #ifndef FUTEX_WAIT_PRIVATE
1263 #define FUTEX_WAIT_PRIVATE FUTEX_WAIT
1264 #define FUTEX_WAKE_PRIVATE FUTEX_WAKE
1265 #endif
1266
1267 /* We should expand the set of operations available in gatomic once we
1268  * have better C11 support in GCC in common distributions (ie: 4.9).
1269  *
1270  * Before then, let's define a couple of useful things for our own
1271  * purposes...
1272  */
1273
1274 #define exchange_acquire(ptr, new) \
1275   __atomic_exchange_4((ptr), (new), __ATOMIC_ACQUIRE)
1276 #define compare_exchange_acquire(ptr, old, new) \
1277   __atomic_compare_exchange_4((ptr), (old), (new), 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)
1278
1279 #define exchange_release(ptr, new) \
1280   __atomic_exchange_4((ptr), (new), __ATOMIC_RELEASE)
1281 #define store_release(ptr, new) \
1282   __atomic_store_4((ptr), (new), __ATOMIC_RELEASE)
1283
1284 /* Our strategy for the mutex is pretty simple:
1285  *
1286  *  0: not in use
1287  *
1288  *  1: acquired by one thread only, no contention
1289  *
1290  *  > 1: contended
1291  *
1292  *
1293  * As such, attempting to acquire the lock should involve an increment.
1294  * If we find that the previous value was 0 then we can return
1295  * immediately.
1296  *
1297  * On unlock, we always store 0 to indicate that the lock is available.
1298  * If the value there was 1 before then we didn't have contention and
1299  * can return immediately.  If the value was something other than 1 then
1300  * we have the contended case and need to wake a waiter.
1301  *
1302  * If it was not 0 then there is another thread holding it and we must
1303  * wait.  We must always ensure that we mark a value >1 while we are
1304  * waiting in order to instruct the holder to do a wake operation on
1305  * unlock.
1306  */
1307
1308 void
1309 g_mutex_init (GMutex *mutex)
1310 {
1311   mutex->i[0] = 0;
1312 }
1313
1314 void
1315 g_mutex_clear (GMutex *mutex)
1316 {
1317   if G_UNLIKELY (mutex->i[0] != 0)
1318     {
1319       fprintf (stderr, "g_mutex_clear() called on uninitialised or locked mutex\n");
1320       g_abort ();
1321     }
1322 }
1323
1324 static void __attribute__((noinline))
1325 g_mutex_lock_slowpath (GMutex *mutex)
1326 {
1327   /* Set to 2 to indicate contention.  If it was zero before then we
1328    * just acquired the lock.
1329    *
1330    * Otherwise, sleep for as long as the 2 remains...
1331    */
1332   while (exchange_acquire (&mutex->i[0], 2) != 0)
1333     syscall (__NR_futex, &mutex->i[0], (gsize) FUTEX_WAIT_PRIVATE, (gsize) 2, NULL);
1334 }
1335
1336 static void __attribute__((noinline))
1337 g_mutex_unlock_slowpath (GMutex *mutex,
1338                          guint   prev)
1339 {
1340   /* We seem to get better code for the uncontended case by splitting
1341    * this out...
1342    */
1343   if G_UNLIKELY (prev == 0)
1344     {
1345       fprintf (stderr, "Attempt to unlock mutex that was not locked\n");
1346       g_abort ();
1347     }
1348
1349   syscall (__NR_futex, &mutex->i[0], (gsize) FUTEX_WAKE_PRIVATE, (gsize) 1, NULL);
1350 }
1351
1352 void
1353 g_mutex_lock (GMutex *mutex)
1354 {
1355   /* 0 -> 1 and we're done.  Anything else, and we need to wait... */
1356   if G_UNLIKELY (g_atomic_int_add (&mutex->i[0], 1) != 0)
1357     g_mutex_lock_slowpath (mutex);
1358 }
1359
1360 void
1361 g_mutex_unlock (GMutex *mutex)
1362 {
1363   guint prev;
1364
1365   prev = exchange_release (&mutex->i[0], 0);
1366
1367   /* 1-> 0 and we're done.  Anything else and we need to signal... */
1368   if G_UNLIKELY (prev != 1)
1369     g_mutex_unlock_slowpath (mutex, prev);
1370 }
1371
1372 gboolean
1373 g_mutex_trylock (GMutex *mutex)
1374 {
1375   guint zero = 0;
1376
1377   /* We don't want to touch the value at all unless we can move it from
1378    * exactly 0 to 1.
1379    */
1380   return compare_exchange_acquire (&mutex->i[0], &zero, 1);
1381 }
1382
1383 /* Condition variables are implemented in a rather simple way as well.
1384  * In many ways, futex() as an abstraction is even more ideally suited
1385  * to condition variables than it is to mutexes.
1386  *
1387  * We store a generation counter.  We sample it with the lock held and
1388  * unlock before sleeping on the futex.
1389  *
1390  * Signalling simply involves increasing the counter and making the
1391  * appropriate futex call.
1392  *
1393  * The only thing that is the slightest bit complicated is timed waits
1394  * because we must convert our absolute time to relative.
1395  */
1396
1397 void
1398 g_cond_init (GCond *cond)
1399 {
1400   cond->i[0] = 0;
1401 }
1402
1403 void
1404 g_cond_clear (GCond *cond)
1405 {
1406 }
1407
1408 void
1409 g_cond_wait (GCond  *cond,
1410              GMutex *mutex)
1411 {
1412   guint sampled = g_atomic_int_get (&cond->i[0]);
1413
1414   g_mutex_unlock (mutex);
1415   syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAIT_PRIVATE, (gsize) sampled, NULL);
1416   g_mutex_lock (mutex);
1417 }
1418
1419 void
1420 g_cond_signal (GCond *cond)
1421 {
1422   g_atomic_int_inc (&cond->i[0]);
1423
1424   syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAKE_PRIVATE, (gsize) 1, NULL);
1425 }
1426
1427 void
1428 g_cond_broadcast (GCond *cond)
1429 {
1430   g_atomic_int_inc (&cond->i[0]);
1431
1432   syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAKE_PRIVATE, (gsize) INT_MAX, NULL);
1433 }
1434
1435 gboolean
1436 g_cond_wait_until (GCond  *cond,
1437                    GMutex *mutex,
1438                    gint64  end_time)
1439 {
1440   struct timespec now;
1441   struct timespec span;
1442   guint sampled;
1443   int res;
1444   gboolean success;
1445
1446   if (end_time < 0)
1447     return FALSE;
1448
1449   clock_gettime (CLOCK_MONOTONIC, &now);
1450   span.tv_sec = (end_time / 1000000) - now.tv_sec;
1451   span.tv_nsec = ((end_time % 1000000) * 1000) - now.tv_nsec;
1452   if (span.tv_nsec < 0)
1453     {
1454       span.tv_nsec += 1000000000;
1455       span.tv_sec--;
1456     }
1457
1458   if (span.tv_sec < 0)
1459     return FALSE;
1460
1461   sampled = cond->i[0];
1462   g_mutex_unlock (mutex);
1463   res = syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAIT_PRIVATE, (gsize) sampled, &span);
1464   success = (res < 0 && errno == ETIMEDOUT) ? FALSE : TRUE;
1465   g_mutex_lock (mutex);
1466
1467   return success;
1468 }
1469
1470 #endif
1471
1472   /* {{{1 Epilogue */
1473 /* vim:set foldmethod=marker: */