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