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