Merge branch '976-disable-assert-checks' into 'master'
[glib.git] / glib / gthread-posix.c
blob5fff514774fc1823a88aeeff2cec8c1251cd5d8c
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gthread.c: posix thread system implementation
5 * Copyright 1998 Sebastian Wilhelmi; University of Karlsruhe
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.
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.
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/>.
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/.
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.
33 * As such, these functions are NOT permitted to call any other part of
34 * GLib.
36 * The thread manipulation functions (create, exit, join, etc.) have
37 * more freedom -- they can do as they please.
40 #include "config.h"
42 #include "gthread.h"
44 #include "gthreadprivate.h"
45 #include "gslice.h"
46 #include "gmessages.h"
47 #include "gstrfuncs.h"
48 #include "gmain.h"
49 #include "gutils.h"
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <pthread.h>
57 #include <sys/time.h>
58 #include <unistd.h>
60 #ifdef HAVE_SCHED_H
61 #include <sched.h>
62 #endif
63 #ifdef G_OS_WIN32
64 #include <windows.h>
65 #endif
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
72 static void
73 g_thread_abort (gint status,
74 const gchar *function)
76 fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s. Aborting.\n",
77 function, strerror (status));
78 g_abort ();
81 /* {{{1 GMutex */
83 #if !defined(USE_NATIVE_MUTEX)
85 static pthread_mutex_t *
86 g_mutex_impl_new (void)
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
95 mutex = malloc (sizeof (pthread_mutex_t));
96 if G_UNLIKELY (mutex == NULL)
97 g_thread_abort (errno, "malloc");
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
105 if G_UNLIKELY ((status = pthread_mutex_init (mutex, pattr)) != 0)
106 g_thread_abort (status, "pthread_mutex_init");
108 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
109 pthread_mutexattr_destroy (&attr);
110 #endif
112 return mutex;
115 static void
116 g_mutex_impl_free (pthread_mutex_t *mutex)
118 pthread_mutex_destroy (mutex);
119 free (mutex);
122 static inline pthread_mutex_t *
123 g_mutex_get_impl (GMutex *mutex)
125 pthread_mutex_t *impl = g_atomic_pointer_get (&mutex->p);
127 if G_UNLIKELY (impl == NULL)
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;
135 return impl;
140 * g_mutex_init:
141 * @mutex: an uninitialized #GMutex
143 * Initializes a #GMutex so that it can be used.
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.
150 * |[<!-- language="C" -->
151 * typedef struct {
152 * GMutex m;
153 * ...
154 * } Blob;
156 * Blob *b;
158 * b = g_new (Blob, 1);
159 * g_mutex_init (&b->m);
160 * ]|
162 * To undo the effect of g_mutex_init() when a mutex is no longer
163 * needed, use g_mutex_clear().
165 * Calling g_mutex_init() on an already initialized #GMutex leads
166 * to undefined behaviour.
168 * Since: 2.32
170 void
171 g_mutex_init (GMutex *mutex)
173 mutex->p = g_mutex_impl_new ();
177 * g_mutex_clear:
178 * @mutex: an initialized #GMutex
180 * Frees the resources allocated to a mutex with g_mutex_init().
182 * This function should not be used with a #GMutex that has been
183 * statically allocated.
185 * Calling g_mutex_clear() on a locked mutex leads to undefined
186 * behaviour.
188 * Sine: 2.32
190 void
191 g_mutex_clear (GMutex *mutex)
193 g_mutex_impl_free (mutex->p);
197 * g_mutex_lock:
198 * @mutex: a #GMutex
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.
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).
209 void
210 g_mutex_lock (GMutex *mutex)
212 gint status;
214 if G_UNLIKELY ((status = pthread_mutex_lock (g_mutex_get_impl (mutex))) != 0)
215 g_thread_abort (status, "pthread_mutex_lock");
219 * g_mutex_unlock:
220 * @mutex: a #GMutex
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.
225 * Calling g_mutex_unlock() on a mutex that is not locked by the
226 * current thread leads to undefined behaviour.
228 void
229 g_mutex_unlock (GMutex *mutex)
231 gint status;
233 if G_UNLIKELY ((status = pthread_mutex_unlock (g_mutex_get_impl (mutex))) != 0)
234 g_thread_abort (status, "pthread_mutex_unlock");
238 * g_mutex_trylock:
239 * @mutex: a #GMutex
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.
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).
250 * Returns: %TRUE if @mutex could be locked
252 gboolean
253 g_mutex_trylock (GMutex *mutex)
255 gint status;
257 if G_LIKELY ((status = pthread_mutex_trylock (g_mutex_get_impl (mutex))) == 0)
258 return TRUE;
260 if G_UNLIKELY (status != EBUSY)
261 g_thread_abort (status, "pthread_mutex_trylock");
263 return FALSE;
266 #endif /* !defined(USE_NATIVE_MUTEX) */
268 /* {{{1 GRecMutex */
270 static pthread_mutex_t *
271 g_rec_mutex_impl_new (void)
273 pthread_mutexattr_t attr;
274 pthread_mutex_t *mutex;
276 mutex = malloc (sizeof (pthread_mutex_t));
277 if G_UNLIKELY (mutex == NULL)
278 g_thread_abort (errno, "malloc");
280 pthread_mutexattr_init (&attr);
281 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
282 pthread_mutex_init (mutex, &attr);
283 pthread_mutexattr_destroy (&attr);
285 return mutex;
288 static void
289 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
291 pthread_mutex_destroy (mutex);
292 free (mutex);
295 static inline pthread_mutex_t *
296 g_rec_mutex_get_impl (GRecMutex *rec_mutex)
298 pthread_mutex_t *impl = g_atomic_pointer_get (&rec_mutex->p);
300 if G_UNLIKELY (impl == NULL)
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;
308 return impl;
312 * g_rec_mutex_init:
313 * @rec_mutex: an uninitialized #GRecMutex
315 * Initializes a #GRecMutex so that it can be used.
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.
321 * It is not necessary to initialise a recursive mutex that has been
322 * statically allocated.
324 * |[<!-- language="C" -->
325 * typedef struct {
326 * GRecMutex m;
327 * ...
328 * } Blob;
330 * Blob *b;
332 * b = g_new (Blob, 1);
333 * g_rec_mutex_init (&b->m);
334 * ]|
336 * Calling g_rec_mutex_init() on an already initialized #GRecMutex
337 * leads to undefined behaviour.
339 * To undo the effect of g_rec_mutex_init() when a recursive mutex
340 * is no longer needed, use g_rec_mutex_clear().
342 * Since: 2.32
344 void
345 g_rec_mutex_init (GRecMutex *rec_mutex)
347 rec_mutex->p = g_rec_mutex_impl_new ();
351 * g_rec_mutex_clear:
352 * @rec_mutex: an initialized #GRecMutex
354 * Frees the resources allocated to a recursive mutex with
355 * g_rec_mutex_init().
357 * This function should not be used with a #GRecMutex that has been
358 * statically allocated.
360 * Calling g_rec_mutex_clear() on a locked recursive mutex leads
361 * to undefined behaviour.
363 * Sine: 2.32
365 void
366 g_rec_mutex_clear (GRecMutex *rec_mutex)
368 g_rec_mutex_impl_free (rec_mutex->p);
372 * g_rec_mutex_lock:
373 * @rec_mutex: a #GRecMutex
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.
382 * Since: 2.32
384 void
385 g_rec_mutex_lock (GRecMutex *mutex)
387 pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
391 * g_rec_mutex_unlock:
392 * @rec_mutex: a #GRecMutex
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.
398 * Calling g_rec_mutex_unlock() on a recursive mutex that is not
399 * locked by the current thread leads to undefined behaviour.
401 * Since: 2.32
403 void
404 g_rec_mutex_unlock (GRecMutex *rec_mutex)
406 pthread_mutex_unlock (rec_mutex->p);
410 * g_rec_mutex_trylock:
411 * @rec_mutex: a #GRecMutex
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.
417 * Returns: %TRUE if @rec_mutex could be locked
419 * Since: 2.32
421 gboolean
422 g_rec_mutex_trylock (GRecMutex *rec_mutex)
424 if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
425 return FALSE;
427 return TRUE;
430 /* {{{1 GRWLock */
432 static pthread_rwlock_t *
433 g_rw_lock_impl_new (void)
435 pthread_rwlock_t *rwlock;
436 gint status;
438 rwlock = malloc (sizeof (pthread_rwlock_t));
439 if G_UNLIKELY (rwlock == NULL)
440 g_thread_abort (errno, "malloc");
442 if G_UNLIKELY ((status = pthread_rwlock_init (rwlock, NULL)) != 0)
443 g_thread_abort (status, "pthread_rwlock_init");
445 return rwlock;
448 static void
449 g_rw_lock_impl_free (pthread_rwlock_t *rwlock)
451 pthread_rwlock_destroy (rwlock);
452 free (rwlock);
455 static inline pthread_rwlock_t *
456 g_rw_lock_get_impl (GRWLock *lock)
458 pthread_rwlock_t *impl = g_atomic_pointer_get (&lock->p);
460 if G_UNLIKELY (impl == NULL)
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;
468 return impl;
472 * g_rw_lock_init:
473 * @rw_lock: an uninitialized #GRWLock
475 * Initializes a #GRWLock so that it can be used.
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.
482 * |[<!-- language="C" -->
483 * typedef struct {
484 * GRWLock l;
485 * ...
486 * } Blob;
488 * Blob *b;
490 * b = g_new (Blob, 1);
491 * g_rw_lock_init (&b->l);
492 * ]|
494 * To undo the effect of g_rw_lock_init() when a lock is no longer
495 * needed, use g_rw_lock_clear().
497 * Calling g_rw_lock_init() on an already initialized #GRWLock leads
498 * to undefined behaviour.
500 * Since: 2.32
502 void
503 g_rw_lock_init (GRWLock *rw_lock)
505 rw_lock->p = g_rw_lock_impl_new ();
509 * g_rw_lock_clear:
510 * @rw_lock: an initialized #GRWLock
512 * Frees the resources allocated to a lock with g_rw_lock_init().
514 * This function should not be used with a #GRWLock that has been
515 * statically allocated.
517 * Calling g_rw_lock_clear() when any thread holds the lock
518 * leads to undefined behaviour.
520 * Sine: 2.32
522 void
523 g_rw_lock_clear (GRWLock *rw_lock)
525 g_rw_lock_impl_free (rw_lock->p);
529 * g_rw_lock_writer_lock:
530 * @rw_lock: a #GRWLock
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.
536 * Since: 2.32
538 void
539 g_rw_lock_writer_lock (GRWLock *rw_lock)
541 int retval = pthread_rwlock_wrlock (g_rw_lock_get_impl (rw_lock));
543 if (retval != 0)
544 g_critical ("Failed to get RW lock %p: %s", rw_lock, g_strerror (retval));
548 * g_rw_lock_writer_trylock:
549 * @rw_lock: a #GRWLock
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.
555 * Returns: %TRUE if @rw_lock could be locked
557 * Since: 2.32
559 gboolean
560 g_rw_lock_writer_trylock (GRWLock *rw_lock)
562 if (pthread_rwlock_trywrlock (g_rw_lock_get_impl (rw_lock)) != 0)
563 return FALSE;
565 return TRUE;
569 * g_rw_lock_writer_unlock:
570 * @rw_lock: a #GRWLock
572 * Release a write lock on @rw_lock.
574 * Calling g_rw_lock_writer_unlock() on a lock that is not held
575 * by the current thread leads to undefined behaviour.
577 * Since: 2.32
579 void
580 g_rw_lock_writer_unlock (GRWLock *rw_lock)
582 pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
586 * g_rw_lock_reader_lock:
587 * @rw_lock: a #GRWLock
589 * Obtain a read lock on @rw_lock. If another thread currently holds
590 * the write lock on @rw_lock or blocks waiting for it, the current
591 * thread will block. Read locks can be taken recursively.
593 * It is implementation-defined how many threads are allowed to
594 * hold read locks on the same lock simultaneously. If the limit is hit,
595 * or if a deadlock is detected, a critical warning will be emitted.
597 * Since: 2.32
599 void
600 g_rw_lock_reader_lock (GRWLock *rw_lock)
602 int retval = pthread_rwlock_rdlock (g_rw_lock_get_impl (rw_lock));
604 if (retval != 0)
605 g_critical ("Failed to get RW lock %p: %s", rw_lock, g_strerror (retval));
609 * g_rw_lock_reader_trylock:
610 * @rw_lock: a #GRWLock
612 * Tries to obtain a read lock on @rw_lock and returns %TRUE if
613 * the read lock was successfully obtained. Otherwise it
614 * returns %FALSE.
616 * Returns: %TRUE if @rw_lock could be locked
618 * Since: 2.32
620 gboolean
621 g_rw_lock_reader_trylock (GRWLock *rw_lock)
623 if (pthread_rwlock_tryrdlock (g_rw_lock_get_impl (rw_lock)) != 0)
624 return FALSE;
626 return TRUE;
630 * g_rw_lock_reader_unlock:
631 * @rw_lock: a #GRWLock
633 * Release a read lock on @rw_lock.
635 * Calling g_rw_lock_reader_unlock() on a lock that is not held
636 * by the current thread leads to undefined behaviour.
638 * Since: 2.32
640 void
641 g_rw_lock_reader_unlock (GRWLock *rw_lock)
643 pthread_rwlock_unlock (g_rw_lock_get_impl (rw_lock));
646 /* {{{1 GCond */
648 #if !defined(USE_NATIVE_MUTEX)
650 static pthread_cond_t *
651 g_cond_impl_new (void)
653 pthread_condattr_t attr;
654 pthread_cond_t *cond;
655 gint status;
657 pthread_condattr_init (&attr);
659 #ifdef HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP
660 #elif defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
661 if G_UNLIKELY ((status = pthread_condattr_setclock (&attr, CLOCK_MONOTONIC)) != 0)
662 g_thread_abort (status, "pthread_condattr_setclock");
663 #else
664 #error Cannot support GCond on your platform.
665 #endif
667 cond = malloc (sizeof (pthread_cond_t));
668 if G_UNLIKELY (cond == NULL)
669 g_thread_abort (errno, "malloc");
671 if G_UNLIKELY ((status = pthread_cond_init (cond, &attr)) != 0)
672 g_thread_abort (status, "pthread_cond_init");
674 pthread_condattr_destroy (&attr);
676 return cond;
679 static void
680 g_cond_impl_free (pthread_cond_t *cond)
682 pthread_cond_destroy (cond);
683 free (cond);
686 static inline pthread_cond_t *
687 g_cond_get_impl (GCond *cond)
689 pthread_cond_t *impl = g_atomic_pointer_get (&cond->p);
691 if G_UNLIKELY (impl == NULL)
693 impl = g_cond_impl_new ();
694 if (!g_atomic_pointer_compare_and_exchange (&cond->p, NULL, impl))
695 g_cond_impl_free (impl);
696 impl = cond->p;
699 return impl;
703 * g_cond_init:
704 * @cond: an uninitialized #GCond
706 * Initialises a #GCond so that it can be used.
708 * This function is useful to initialise a #GCond that has been
709 * allocated as part of a larger structure. It is not necessary to
710 * initialise a #GCond that has been statically allocated.
712 * To undo the effect of g_cond_init() when a #GCond is no longer
713 * needed, use g_cond_clear().
715 * Calling g_cond_init() on an already-initialised #GCond leads
716 * to undefined behaviour.
718 * Since: 2.32
720 void
721 g_cond_init (GCond *cond)
723 cond->p = g_cond_impl_new ();
727 * g_cond_clear:
728 * @cond: an initialised #GCond
730 * Frees the resources allocated to a #GCond with g_cond_init().
732 * This function should not be used with a #GCond that has been
733 * statically allocated.
735 * Calling g_cond_clear() for a #GCond on which threads are
736 * blocking leads to undefined behaviour.
738 * Since: 2.32
740 void
741 g_cond_clear (GCond *cond)
743 g_cond_impl_free (cond->p);
747 * g_cond_wait:
748 * @cond: a #GCond
749 * @mutex: a #GMutex that is currently locked
751 * Atomically releases @mutex and waits until @cond is signalled.
752 * When this function returns, @mutex is locked again and owned by the
753 * calling thread.
755 * When using condition variables, it is possible that a spurious wakeup
756 * may occur (ie: g_cond_wait() returns even though g_cond_signal() was
757 * not called). It's also possible that a stolen wakeup may occur.
758 * This is when g_cond_signal() is called, but another thread acquires
759 * @mutex before this thread and modifies the state of the program in
760 * such a way that when g_cond_wait() is able to return, the expected
761 * condition is no longer met.
763 * For this reason, g_cond_wait() must always be used in a loop. See
764 * the documentation for #GCond for a complete example.
766 void
767 g_cond_wait (GCond *cond,
768 GMutex *mutex)
770 gint status;
772 if G_UNLIKELY ((status = pthread_cond_wait (g_cond_get_impl (cond), g_mutex_get_impl (mutex))) != 0)
773 g_thread_abort (status, "pthread_cond_wait");
777 * g_cond_signal:
778 * @cond: a #GCond
780 * If threads are waiting for @cond, at least one of them is unblocked.
781 * If no threads are waiting for @cond, this function has no effect.
782 * It is good practice to hold the same lock as the waiting thread
783 * while calling this function, though not required.
785 void
786 g_cond_signal (GCond *cond)
788 gint status;
790 if G_UNLIKELY ((status = pthread_cond_signal (g_cond_get_impl (cond))) != 0)
791 g_thread_abort (status, "pthread_cond_signal");
795 * g_cond_broadcast:
796 * @cond: a #GCond
798 * If threads are waiting for @cond, all of them are unblocked.
799 * If no threads are waiting for @cond, this function has no effect.
800 * It is good practice to lock the same mutex as the waiting threads
801 * while calling this function, though not required.
803 void
804 g_cond_broadcast (GCond *cond)
806 gint status;
808 if G_UNLIKELY ((status = pthread_cond_broadcast (g_cond_get_impl (cond))) != 0)
809 g_thread_abort (status, "pthread_cond_broadcast");
813 * g_cond_wait_until:
814 * @cond: a #GCond
815 * @mutex: a #GMutex that is currently locked
816 * @end_time: the monotonic time to wait until
818 * Waits until either @cond is signalled or @end_time has passed.
820 * As with g_cond_wait() it is possible that a spurious or stolen wakeup
821 * could occur. For that reason, waiting on a condition variable should
822 * always be in a loop, based on an explicitly-checked predicate.
824 * %TRUE is returned if the condition variable was signalled (or in the
825 * case of a spurious wakeup). %FALSE is returned if @end_time has
826 * passed.
828 * The following code shows how to correctly perform a timed wait on a
829 * condition variable (extending the example presented in the
830 * documentation for #GCond):
832 * |[<!-- language="C" -->
833 * gpointer
834 * pop_data_timed (void)
836 * gint64 end_time;
837 * gpointer data;
839 * g_mutex_lock (&data_mutex);
841 * end_time = g_get_monotonic_time () + 5 * G_TIME_SPAN_SECOND;
842 * while (!current_data)
843 * if (!g_cond_wait_until (&data_cond, &data_mutex, end_time))
845 * // timeout has passed.
846 * g_mutex_unlock (&data_mutex);
847 * return NULL;
850 * // there is data for us
851 * data = current_data;
852 * current_data = NULL;
854 * g_mutex_unlock (&data_mutex);
856 * return data;
858 * ]|
860 * Notice that the end time is calculated once, before entering the
861 * loop and reused. This is the motivation behind the use of absolute
862 * time on this API -- if a relative time of 5 seconds were passed
863 * directly to the call and a spurious wakeup occurred, the program would
864 * have to start over waiting again (which would lead to a total wait
865 * time of more than 5 seconds).
867 * Returns: %TRUE on a signal, %FALSE on a timeout
868 * Since: 2.32
870 gboolean
871 g_cond_wait_until (GCond *cond,
872 GMutex *mutex,
873 gint64 end_time)
875 struct timespec ts;
876 gint status;
878 #ifdef HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP
879 /* end_time is given relative to the monotonic clock as returned by
880 * g_get_monotonic_time().
882 * Since this pthreads wants the relative time, convert it back again.
885 gint64 now = g_get_monotonic_time ();
886 gint64 relative;
888 if (end_time <= now)
889 return FALSE;
891 relative = end_time - now;
893 ts.tv_sec = relative / 1000000;
894 ts.tv_nsec = (relative % 1000000) * 1000;
896 if ((status = pthread_cond_timedwait_relative_np (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &ts)) == 0)
897 return TRUE;
899 #elif defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
900 /* This is the exact check we used during init to set the clock to
901 * monotonic, so if we're in this branch, timedwait() will already be
902 * expecting a monotonic clock.
905 ts.tv_sec = end_time / 1000000;
906 ts.tv_nsec = (end_time % 1000000) * 1000;
908 if ((status = pthread_cond_timedwait (g_cond_get_impl (cond), g_mutex_get_impl (mutex), &ts)) == 0)
909 return TRUE;
911 #else
912 #error Cannot support GCond on your platform.
913 #endif
915 if G_UNLIKELY (status != ETIMEDOUT)
916 g_thread_abort (status, "pthread_cond_timedwait");
918 return FALSE;
921 #endif /* defined(USE_NATIVE_MUTEX) */
923 /* {{{1 GPrivate */
926 * GPrivate:
928 * The #GPrivate struct is an opaque data structure to represent a
929 * thread-local data key. It is approximately equivalent to the
930 * pthread_setspecific()/pthread_getspecific() APIs on POSIX and to
931 * TlsSetValue()/TlsGetValue() on Windows.
933 * If you don't already know why you might want this functionality,
934 * then you probably don't need it.
936 * #GPrivate is a very limited resource (as far as 128 per program,
937 * shared between all libraries). It is also not possible to destroy a
938 * #GPrivate after it has been used. As such, it is only ever acceptable
939 * to use #GPrivate in static scope, and even then sparingly so.
941 * See G_PRIVATE_INIT() for a couple of examples.
943 * The #GPrivate structure should be considered opaque. It should only
944 * be accessed via the g_private_ functions.
948 * G_PRIVATE_INIT:
949 * @notify: a #GDestroyNotify
951 * A macro to assist with the static initialisation of a #GPrivate.
953 * This macro is useful for the case that a #GDestroyNotify function
954 * should be associated with the key. This is needed when the key will be
955 * used to point at memory that should be deallocated when the thread
956 * exits.
958 * Additionally, the #GDestroyNotify will also be called on the previous
959 * value stored in the key when g_private_replace() is used.
961 * If no #GDestroyNotify is needed, then use of this macro is not
962 * required -- if the #GPrivate is declared in static scope then it will
963 * be properly initialised by default (ie: to all zeros). See the
964 * examples below.
966 * |[<!-- language="C" -->
967 * static GPrivate name_key = G_PRIVATE_INIT (g_free);
969 * // return value should not be freed
970 * const gchar *
971 * get_local_name (void)
973 * return g_private_get (&name_key);
976 * void
977 * set_local_name (const gchar *name)
979 * g_private_replace (&name_key, g_strdup (name));
983 * static GPrivate count_key; // no free function
985 * gint
986 * get_local_count (void)
988 * return GPOINTER_TO_INT (g_private_get (&count_key));
991 * void
992 * set_local_count (gint count)
994 * g_private_set (&count_key, GINT_TO_POINTER (count));
996 * ]|
998 * Since: 2.32
1001 static pthread_key_t *
1002 g_private_impl_new (GDestroyNotify notify)
1004 pthread_key_t *key;
1005 gint status;
1007 key = malloc (sizeof (pthread_key_t));
1008 if G_UNLIKELY (key == NULL)
1009 g_thread_abort (errno, "malloc");
1010 status = pthread_key_create (key, notify);
1011 if G_UNLIKELY (status != 0)
1012 g_thread_abort (status, "pthread_key_create");
1014 return key;
1017 static void
1018 g_private_impl_free (pthread_key_t *key)
1020 gint status;
1022 status = pthread_key_delete (*key);
1023 if G_UNLIKELY (status != 0)
1024 g_thread_abort (status, "pthread_key_delete");
1025 free (key);
1028 static inline pthread_key_t *
1029 g_private_get_impl (GPrivate *key)
1031 pthread_key_t *impl = g_atomic_pointer_get (&key->p);
1033 if G_UNLIKELY (impl == NULL)
1035 impl = g_private_impl_new (key->notify);
1036 if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
1038 g_private_impl_free (impl);
1039 impl = key->p;
1043 return impl;
1047 * g_private_get:
1048 * @key: a #GPrivate
1050 * Returns the current value of the thread local variable @key.
1052 * If the value has not yet been set in this thread, %NULL is returned.
1053 * Values are never copied between threads (when a new thread is
1054 * created, for example).
1056 * Returns: the thread-local value
1058 gpointer
1059 g_private_get (GPrivate *key)
1061 /* quote POSIX: No errors are returned from pthread_getspecific(). */
1062 return pthread_getspecific (*g_private_get_impl (key));
1066 * g_private_set:
1067 * @key: a #GPrivate
1068 * @value: the new value
1070 * Sets the thread local variable @key to have the value @value in the
1071 * current thread.
1073 * This function differs from g_private_replace() in the following way:
1074 * the #GDestroyNotify for @key is not called on the old value.
1076 void
1077 g_private_set (GPrivate *key,
1078 gpointer value)
1080 gint status;
1082 if G_UNLIKELY ((status = pthread_setspecific (*g_private_get_impl (key), value)) != 0)
1083 g_thread_abort (status, "pthread_setspecific");
1087 * g_private_replace:
1088 * @key: a #GPrivate
1089 * @value: the new value
1091 * Sets the thread local variable @key to have the value @value in the
1092 * current thread.
1094 * This function differs from g_private_set() in the following way: if
1095 * the previous value was non-%NULL then the #GDestroyNotify handler for
1096 * @key is run on it.
1098 * Since: 2.32
1100 void
1101 g_private_replace (GPrivate *key,
1102 gpointer value)
1104 pthread_key_t *impl = g_private_get_impl (key);
1105 gpointer old;
1106 gint status;
1108 old = pthread_getspecific (*impl);
1109 if (old && key->notify)
1110 key->notify (old);
1112 if G_UNLIKELY ((status = pthread_setspecific (*impl, value)) != 0)
1113 g_thread_abort (status, "pthread_setspecific");
1116 /* {{{1 GThread */
1118 #define posix_check_err(err, name) G_STMT_START{ \
1119 int error = (err); \
1120 if (error) \
1121 g_error ("file %s: line %d (%s): error '%s' during '%s'", \
1122 __FILE__, __LINE__, G_STRFUNC, \
1123 g_strerror (error), name); \
1124 }G_STMT_END
1126 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
1128 typedef struct
1130 GRealThread thread;
1132 pthread_t system_thread;
1133 gboolean joined;
1134 GMutex lock;
1135 } GThreadPosix;
1137 void
1138 g_system_thread_free (GRealThread *thread)
1140 GThreadPosix *pt = (GThreadPosix *) thread;
1142 if (!pt->joined)
1143 pthread_detach (pt->system_thread);
1145 g_mutex_clear (&pt->lock);
1147 g_slice_free (GThreadPosix, pt);
1150 GRealThread *
1151 g_system_thread_new (GThreadFunc thread_func,
1152 gulong stack_size,
1153 GError **error)
1155 GThreadPosix *thread;
1156 pthread_attr_t attr;
1157 gint ret;
1159 thread = g_slice_new0 (GThreadPosix);
1161 posix_check_cmd (pthread_attr_init (&attr));
1163 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1164 if (stack_size)
1166 #ifdef _SC_THREAD_STACK_MIN
1167 long min_stack_size = sysconf (_SC_THREAD_STACK_MIN);
1168 if (min_stack_size >= 0)
1169 stack_size = MAX (min_stack_size, stack_size);
1170 #endif /* _SC_THREAD_STACK_MIN */
1171 /* No error check here, because some systems can't do it and
1172 * we simply don't want threads to fail because of that. */
1173 pthread_attr_setstacksize (&attr, stack_size);
1175 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
1177 ret = pthread_create (&thread->system_thread, &attr, (void* (*)(void*))thread_func, thread);
1179 posix_check_cmd (pthread_attr_destroy (&attr));
1181 if (ret == EAGAIN)
1183 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
1184 "Error creating thread: %s", g_strerror (ret));
1185 g_slice_free (GThreadPosix, thread);
1186 return NULL;
1189 posix_check_err (ret, "pthread_create");
1191 g_mutex_init (&thread->lock);
1193 return (GRealThread *) thread;
1197 * g_thread_yield:
1199 * Causes the calling thread to voluntarily relinquish the CPU, so
1200 * that other threads can run.
1202 * This function is often used as a method to make busy wait less evil.
1204 void
1205 g_thread_yield (void)
1207 sched_yield ();
1210 void
1211 g_system_thread_wait (GRealThread *thread)
1213 GThreadPosix *pt = (GThreadPosix *) thread;
1215 g_mutex_lock (&pt->lock);
1217 if (!pt->joined)
1219 posix_check_cmd (pthread_join (pt->system_thread, NULL));
1220 pt->joined = TRUE;
1223 g_mutex_unlock (&pt->lock);
1226 void
1227 g_system_thread_exit (void)
1229 pthread_exit (NULL);
1232 void
1233 g_system_thread_set_name (const gchar *name)
1235 #if defined(HAVE_PTHREAD_SETNAME_NP_WITH_TID)
1236 pthread_setname_np (pthread_self(), name); /* on Linux and Solaris */
1237 #elif defined(HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID)
1238 pthread_setname_np (name); /* on OS X and iOS */
1239 #endif
1242 /* {{{1 GMutex and GCond futex implementation */
1244 #if defined(USE_NATIVE_MUTEX)
1246 #include <linux/futex.h>
1247 #include <sys/syscall.h>
1249 #ifndef FUTEX_WAIT_PRIVATE
1250 #define FUTEX_WAIT_PRIVATE FUTEX_WAIT
1251 #define FUTEX_WAKE_PRIVATE FUTEX_WAKE
1252 #endif
1254 /* We should expand the set of operations available in gatomic once we
1255 * have better C11 support in GCC in common distributions (ie: 4.9).
1257 * Before then, let's define a couple of useful things for our own
1258 * purposes...
1261 #define exchange_acquire(ptr, new) \
1262 __atomic_exchange_4((ptr), (new), __ATOMIC_ACQUIRE)
1263 #define compare_exchange_acquire(ptr, old, new) \
1264 __atomic_compare_exchange_4((ptr), (old), (new), 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)
1266 #define exchange_release(ptr, new) \
1267 __atomic_exchange_4((ptr), (new), __ATOMIC_RELEASE)
1268 #define store_release(ptr, new) \
1269 __atomic_store_4((ptr), (new), __ATOMIC_RELEASE)
1271 /* Our strategy for the mutex is pretty simple:
1273 * 0: not in use
1275 * 1: acquired by one thread only, no contention
1277 * > 1: contended
1280 * As such, attempting to acquire the lock should involve an increment.
1281 * If we find that the previous value was 0 then we can return
1282 * immediately.
1284 * On unlock, we always store 0 to indicate that the lock is available.
1285 * If the value there was 1 before then we didn't have contention and
1286 * can return immediately. If the value was something other than 1 then
1287 * we have the contended case and need to wake a waiter.
1289 * If it was not 0 then there is another thread holding it and we must
1290 * wait. We must always ensure that we mark a value >1 while we are
1291 * waiting in order to instruct the holder to do a wake operation on
1292 * unlock.
1295 void
1296 g_mutex_init (GMutex *mutex)
1298 mutex->i[0] = 0;
1301 void
1302 g_mutex_clear (GMutex *mutex)
1304 if G_UNLIKELY (mutex->i[0] != 0)
1306 fprintf (stderr, "g_mutex_clear() called on uninitialised or locked mutex\n");
1307 g_abort ();
1311 static void __attribute__((noinline))
1312 g_mutex_lock_slowpath (GMutex *mutex)
1314 /* Set to 2 to indicate contention. If it was zero before then we
1315 * just acquired the lock.
1317 * Otherwise, sleep for as long as the 2 remains...
1319 while (exchange_acquire (&mutex->i[0], 2) != 0)
1320 syscall (__NR_futex, &mutex->i[0], (gsize) FUTEX_WAIT_PRIVATE, (gsize) 2, NULL);
1323 static void __attribute__((noinline))
1324 g_mutex_unlock_slowpath (GMutex *mutex,
1325 guint prev)
1327 /* We seem to get better code for the uncontended case by splitting
1328 * this out...
1330 if G_UNLIKELY (prev == 0)
1332 fprintf (stderr, "Attempt to unlock mutex that was not locked\n");
1333 g_abort ();
1336 syscall (__NR_futex, &mutex->i[0], (gsize) FUTEX_WAKE_PRIVATE, (gsize) 1, NULL);
1339 void
1340 g_mutex_lock (GMutex *mutex)
1342 /* 0 -> 1 and we're done. Anything else, and we need to wait... */
1343 if G_UNLIKELY (g_atomic_int_add (&mutex->i[0], 1) != 0)
1344 g_mutex_lock_slowpath (mutex);
1347 void
1348 g_mutex_unlock (GMutex *mutex)
1350 guint prev;
1352 prev = exchange_release (&mutex->i[0], 0);
1354 /* 1-> 0 and we're done. Anything else and we need to signal... */
1355 if G_UNLIKELY (prev != 1)
1356 g_mutex_unlock_slowpath (mutex, prev);
1359 gboolean
1360 g_mutex_trylock (GMutex *mutex)
1362 guint zero = 0;
1364 /* We don't want to touch the value at all unless we can move it from
1365 * exactly 0 to 1.
1367 return compare_exchange_acquire (&mutex->i[0], &zero, 1);
1370 /* Condition variables are implemented in a rather simple way as well.
1371 * In many ways, futex() as an abstraction is even more ideally suited
1372 * to condition variables than it is to mutexes.
1374 * We store a generation counter. We sample it with the lock held and
1375 * unlock before sleeping on the futex.
1377 * Signalling simply involves increasing the counter and making the
1378 * appropriate futex call.
1380 * The only thing that is the slightest bit complicated is timed waits
1381 * because we must convert our absolute time to relative.
1384 void
1385 g_cond_init (GCond *cond)
1387 cond->i[0] = 0;
1390 void
1391 g_cond_clear (GCond *cond)
1395 void
1396 g_cond_wait (GCond *cond,
1397 GMutex *mutex)
1399 guint sampled = g_atomic_int_get (&cond->i[0]);
1401 g_mutex_unlock (mutex);
1402 syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAIT_PRIVATE, (gsize) sampled, NULL);
1403 g_mutex_lock (mutex);
1406 void
1407 g_cond_signal (GCond *cond)
1409 g_atomic_int_inc (&cond->i[0]);
1411 syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAKE_PRIVATE, (gsize) 1, NULL);
1414 void
1415 g_cond_broadcast (GCond *cond)
1417 g_atomic_int_inc (&cond->i[0]);
1419 syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAKE_PRIVATE, (gsize) INT_MAX, NULL);
1422 gboolean
1423 g_cond_wait_until (GCond *cond,
1424 GMutex *mutex,
1425 gint64 end_time)
1427 struct timespec now;
1428 struct timespec span;
1429 guint sampled;
1430 int res;
1432 if (end_time < 0)
1433 return FALSE;
1435 clock_gettime (CLOCK_MONOTONIC, &now);
1436 span.tv_sec = (end_time / 1000000) - now.tv_sec;
1437 span.tv_nsec = ((end_time % 1000000) * 1000) - now.tv_nsec;
1438 if (span.tv_nsec < 0)
1440 span.tv_nsec += 1000000000;
1441 span.tv_sec--;
1444 if (span.tv_sec < 0)
1445 return FALSE;
1447 sampled = cond->i[0];
1448 g_mutex_unlock (mutex);
1449 res = syscall (__NR_futex, &cond->i[0], (gsize) FUTEX_WAIT_PRIVATE, (gsize) sampled, &span);
1450 g_mutex_lock (mutex);
1452 return (res < 0 && errno == ETIMEDOUT) ? FALSE : TRUE;
1455 #endif
1457 /* {{{1 Epilogue */
1458 /* vim:set foldmethod=marker: */