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 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, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
30 /* The GMutex, GCond and GPrivate implementations in this file are some
31 * of the lowest-level code in GLib. All other parts of GLib (messages,
32 * memory, slices, etc) assume that they can freely use these facilities
33 * without risking recursion.
35 * As such, these functions are NOT permitted to call any other part of
38 * The thread manipulation functions (create, exit, join, etc.) have
39 * more freedom -- they can do as they please.
46 #include "gthreadprivate.h"
48 #include "gmessages.h"
49 #include "gstrfuncs.h"
57 #ifdef HAVE_SYS_TIME_H
58 # include <sys/time.h>
69 g_thread_abort (gint status,
70 const gchar *function)
72 fprintf (stderr, "GLib (gthread-posix.c): Unexpected error from C library during '%s': %s. Aborting.\n",
73 strerror (status), function);
81 * @mutex: an uninitialized #GMutex
83 * Initializes a #GMutex so that it can be used.
85 * This function is useful to initialize a mutex that has been
86 * allocated on the stack, or as part of a larger structure.
87 * It is not necessary to initialize a mutex that has been
88 * created with g_mutex_new(). Also see #G_MUTEX_INIT for an
89 * alternative way to initialize statically allocated mutexes.
99 * b = g_new (Blob, 1);
100 * g_mutex_init (&b->m);
103 * To undo the effect of g_mutex_init() when a mutex is no longer
104 * needed, use g_mutex_clear().
106 * Calling g_mutex_init() on an already initialized #GMutex leads
107 * to undefined behaviour.
112 g_mutex_init (GMutex *mutex)
115 pthread_mutexattr_t *pattr = NULL;
116 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
117 pthread_mutexattr_t attr;
118 pthread_mutexattr_init (&attr);
119 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
123 if G_UNLIKELY ((status = pthread_mutex_init (&mutex->impl, pattr)) != 0)
124 g_thread_abort (status, "pthread_mutex_init");
126 #ifdef PTHREAD_ADAPTIVE_MUTEX_NP
127 pthread_mutexattr_destroy (&attr);
133 * @mutex: an initialized #GMutex
135 * Frees the resources allocated to a mutex with g_mutex_init().
137 * #GMutexes that have have been created with g_mutex_new() should
138 * be freed with g_mutex_free() instead.
140 * Calling g_mutex_clear() on a locked mutex leads to undefined
146 g_mutex_clear (GMutex *mutex)
150 if G_UNLIKELY ((status = pthread_mutex_destroy (&mutex->impl)) != 0)
151 g_thread_abort (status, "pthread_mutex_destroy");
158 * Locks @mutex. If @mutex is already locked by another thread, the
159 * current thread will block until @mutex is unlocked by the other
162 * This function can be used even if g_thread_init() has not yet been
163 * called, and, in that case, will do nothing.
165 * <note>#GMutex is neither guaranteed to be recursive nor to be
166 * non-recursive, i.e. a thread could deadlock while calling
167 * g_mutex_lock(), if it already has locked @mutex. Use
168 * #GRecMutex if you need recursive mutexes.</note>
171 g_mutex_lock (GMutex *mutex)
175 if G_UNLIKELY ((status = pthread_mutex_lock (&mutex->impl)) != 0)
176 g_thread_abort (status, "pthread_mutex_lock");
183 * Unlocks @mutex. If another thread is blocked in a g_mutex_lock()
184 * call for @mutex, it will become unblocked and can lock @mutex itself.
186 * Calling g_mutex_unlock() on a mutex that is not locked by the
187 * current thread leads to undefined behaviour.
189 * This function can be used even if g_thread_init() has not yet been
190 * called, and, in that case, will do nothing.
193 g_mutex_unlock (GMutex *mutex)
197 if G_UNLIKELY ((status = pthread_mutex_unlock (&mutex->impl)) != 0)
198 g_thread_abort (status, "pthread_mutex_lock");
205 * Tries to lock @mutex. If @mutex is already locked by another thread,
206 * it immediately returns %FALSE. Otherwise it locks @mutex and returns
209 * This function can be used even if g_thread_init() has not yet been
210 * called, and, in that case, will immediately return %TRUE.
212 * <note>#GMutex is neither guaranteed to be recursive nor to be
213 * non-recursive, i.e. the return value of g_mutex_trylock() could be
214 * both %FALSE or %TRUE, if the current thread already has locked
215 * @mutex. Use #GRecMutex if you need recursive mutexes.</note>
217 * Returns: %TRUE if @mutex could be locked
220 g_mutex_trylock (GMutex *mutex)
224 if G_LIKELY ((status = pthread_mutex_trylock (&mutex->impl)) == 0)
227 if G_UNLIKELY (status != EBUSY)
228 g_thread_abort (status, "pthread_mutex_trylock");
235 static pthread_mutex_t *
236 g_rec_mutex_impl_new (void)
238 pthread_mutexattr_t attr;
239 pthread_mutex_t *mutex;
241 mutex = g_slice_new (pthread_mutex_t);
242 pthread_mutexattr_init (&attr);
243 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
244 pthread_mutex_init (mutex, &attr);
245 pthread_mutexattr_destroy (&attr);
251 g_rec_mutex_impl_free (pthread_mutex_t *mutex)
253 pthread_mutex_destroy (mutex);
254 g_slice_free (pthread_mutex_t, mutex);
257 static pthread_mutex_t *
258 g_rec_mutex_get_impl (GRecMutex *mutex)
260 pthread_mutex_t *impl = mutex->impl;
262 if G_UNLIKELY (mutex->impl == NULL)
264 impl = g_rec_mutex_impl_new ();
265 if (!g_atomic_pointer_compare_and_exchange (&mutex->impl, NULL, impl))
266 g_rec_mutex_impl_free (impl);
275 * @rec_mutex: an uninitialized #GRecMutex
277 * Initializes a #GRecMutex so that it can be used.
279 * This function is useful to initialize a recursive mutex
280 * that has been allocated on the stack, or as part of a larger
282 * It is not necessary to initialize a recursive mutex that has
283 * been created with g_rec_mutex_new(). Also see #G_REC_MUTEX_INIT
284 * for an alternative way to initialize statically allocated
295 * b = g_new (Blob, 1);
296 * g_rec_mutex_init (&b->m);
299 * Calling g_rec_mutex_init() on an already initialized #GRecMutex
300 * leads to undefined behaviour.
302 * To undo the effect of g_rec_mutex_init() when a recursive mutex
303 * is no longer needed, use g_rec_mutex_clear().
308 g_rec_mutex_init (GRecMutex *rec_mutex)
310 rec_mutex->impl = g_rec_mutex_impl_new ();
315 * @rec_mutex: an initialized #GRecMutex
317 * Frees the resources allocated to a recursive mutex with
318 * g_rec_mutex_init().
320 * #GRecMutexes that have have been created with g_rec_mutex_new()
321 * should be freed with g_rec_mutex_free() instead.
323 * Calling g_rec_mutex_clear() on a locked recursive mutex leads
324 * to undefined behaviour.
329 g_rec_mutex_clear (GRecMutex *rec_mutex)
332 g_rec_mutex_impl_free (rec_mutex->impl);
337 * @rec_mutex: a #GRecMutex
339 * Locks @rec_mutex. If @rec_mutex is already locked by another
340 * thread, the current thread will block until @rec_mutex is
341 * unlocked by the other thread. If @rec_mutex is already locked
342 * by the current thread, the 'lock count' of @rec_mutex is increased.
343 * The mutex will only become available again when it is unlocked
344 * as many times as it has been locked.
349 g_rec_mutex_lock (GRecMutex *mutex)
351 pthread_mutex_lock (g_rec_mutex_get_impl (mutex));
355 * g_rec_mutex_unlock:
356 * @rec_mutex: a #RecGMutex
358 * Unlocks @rec_mutex. If another thread is blocked in a
359 * g_rec_mutex_lock() call for @rec_mutex, it will become unblocked
360 * and can lock @rec_mutex itself.
362 * Calling g_rec_mutex_unlock() on a recursive mutex that is not
363 * locked by the current thread leads to undefined behaviour.
368 g_rec_mutex_unlock (GRecMutex *rec_mutex)
370 pthread_mutex_unlock (rec_mutex->impl);
374 * g_rec_mutex_trylock:
375 * @rec_mutex: a #GRecMutex
377 * Tries to lock @rec_mutex. If @rec_mutex is already locked
378 * by another thread, it immediately returns %FALSE. Otherwise
379 * it locks @rec_mutex and returns %TRUE.
381 * Returns: %TRUE if @rec_mutex could be locked
386 g_rec_mutex_trylock (GRecMutex *rec_mutex)
388 if (pthread_mutex_trylock (g_rec_mutex_get_impl (rec_mutex)) != 0)
398 * @lock: an uninitialized #GRWLock
400 * Initializes a #GRWLock so that it can be used.
402 * This function is useful to initialize a lock that has been
403 * allocated on the stack, or as part of a larger structure.
404 * Also see #G_RW_LOCK_INIT for an alternative way to initialize
405 * statically allocated locks.
415 * b = g_new (Blob, 1);
416 * g_rw_lock_init (&b->l);
419 * To undo the effect of g_rw_lock_init() when a lock is no longer
420 * needed, use g_rw_lock_clear().
422 * Calling g_rw_lock_init() on an already initialized #GRWLock leads
423 * to undefined behaviour.
428 g_rw_lock_init (GRWLock *lock)
430 pthread_rwlock_init (&lock->impl, NULL);
435 * @lock: an initialized #GRWLock
437 * Frees the resources allocated to a lock with g_rw_lock_init().
439 * Calling g_rw_lock_clear() when any thread holds the lock
440 * leads to undefined behaviour.
445 g_rw_lock_clear (GRWLock *lock)
447 pthread_rwlock_destroy (&lock->impl);
451 * g_rw_lock_writer_lock:
454 * Obtain a write lock on @lock. If any thread already holds
455 * a read or write lock on @lock, the current thread will block
456 * until all other threads have dropped their locks on @lock.
461 g_rw_lock_writer_lock (GRWLock *lock)
463 pthread_rwlock_wrlock (&lock->impl);
467 * g_rw_lock_writer_trylock:
470 * Tries to obtain a write lock on @lock. If any other thread holds
471 * a read or write lock on @lock, it immediately returns %FALSE.
472 * Otherwise it locks @lock and returns %TRUE.
474 * Returns: %TRUE if @lock could be locked
479 g_rw_lock_writer_trylock (GRWLock *lock)
481 if (pthread_rwlock_trywrlock (&lock->impl) != 0)
488 * g_rw_lock_writer_unlock:
491 * Release a write lock on @lock.
493 * Calling g_rw_lock_writer_unlock() on a lock that is not held
494 * by the current thread leads to undefined behaviour.
499 g_rw_lock_writer_unlock (GRWLock *lock)
501 pthread_rwlock_unlock (&lock->impl);
505 * g_rw_lock_reader_lock:
508 * Obtain a read lock on @lock. If another thread currently holds
509 * the write lock on @lock or blocks waiting for it, the current
510 * thread will block. Read locks can be taken recursively.
512 * It is implementation-defined how many threads are allowed to
513 * hold read locks on the same lock simultaneously.
518 g_rw_lock_reader_lock (GRWLock *lock)
520 pthread_rwlock_rdlock (&lock->impl);
524 * g_rw_lock_reader_trylock:
527 * Tries to obtain a read lock on @lock and returns %TRUE if
528 * the read lock was successfully obtained. Otherwise it
531 * Returns: %TRUE if @lock could be locked
536 g_rw_lock_reader_trylock (GRWLock *lock)
538 if (pthread_rwlock_tryrdlock (&lock->impl) != 0)
545 * g_rw_lock_reader_unlock:
548 * Release a read lock on @lock.
550 * Calling g_rw_lock_reader_unlock() on a lock that is not held
551 * by the current thread leads to undefined behaviour.
556 g_rw_lock_reader_unlock (GRWLock *lock)
558 pthread_rwlock_unlock (&lock->impl);
565 * @cond: an uninitialized #GCond
567 * Initialized a #GCond so that it can be used.
569 * This function is useful to initialize a #GCond that has been
570 * allocated on the stack, or as part of a larger structure.
571 * It is not necessary to initialize a #GCond that has been
572 * created with g_cond_new(). Also see #G_COND_INIT for an
573 * alternative way to initialize statically allocated #GConds.
575 * To undo the effect of g_cond_init() when a #GCond is no longer
576 * needed, use g_cond_clear().
578 * Calling g_cond_init() on an already initialized #GCond leads
579 * to undefined behaviour.
584 g_cond_init (GCond *cond)
588 if G_UNLIKELY ((status = pthread_cond_init (&cond->impl, NULL)) != 0)
589 g_thread_abort (status, "pthread_cond_init");
594 * @cond: an initialized #GCond
596 * Frees the resources allocated to a #GCond with g_cond_init().
598 * #GConds that have been created with g_cond_new() should
599 * be freed with g_cond_free() instead.
601 * Calling g_cond_clear() for a #GCond on which threads are
602 * blocking leads to undefined behaviour.
607 g_cond_clear (GCond *cond)
611 if G_UNLIKELY ((status = pthread_cond_destroy (&cond->impl)) != 0)
612 g_thread_abort (status, "pthread_cond_destroy");
618 * @mutex: a #GMutex that is currently locked
620 * Waits until this thread is woken up on @cond. The @mutex is unlocked
621 * before falling asleep and locked again before resuming.
623 * This function can be used even if g_thread_init() has not yet been
624 * called, and, in that case, will immediately return.
627 g_cond_wait (GCond *cond,
632 if G_UNLIKELY ((status = pthread_cond_wait (&cond->impl, &mutex->impl)) != 0)
633 g_thread_abort (status, "pthread_cond_wait");
640 * If threads are waiting for @cond, at least one of them is unblocked.
641 * If no threads are waiting for @cond, this function has no effect.
642 * It is good practice to hold the same lock as the waiting thread
643 * while calling this function, though not required.
645 * This function can be used even if g_thread_init() has not yet been
646 * called, and, in that case, will do nothing.
649 g_cond_signal (GCond *cond)
653 if G_UNLIKELY ((status = pthread_cond_signal (&cond->impl)) != 0)
654 g_thread_abort (status, "pthread_cond_signal");
661 * If threads are waiting for @cond, all of them are unblocked.
662 * If no threads are waiting for @cond, this function has no effect.
663 * It is good practice to lock the same mutex as the waiting threads
664 * while calling this function, though not required.
666 * This function can be used even if g_thread_init() has not yet been
667 * called, and, in that case, will do nothing.
670 g_cond_broadcast (GCond *cond)
674 if G_UNLIKELY ((status = pthread_cond_broadcast (&cond->impl)) != 0)
675 g_thread_abort (status, "pthread_cond_broadcast");
681 * @mutex: a #GMutex that is currently locked
682 * @abs_time: a #GTimeVal, determining the final time
684 * Waits until this thread is woken up on @cond, but not longer than
685 * until the time specified by @abs_time. The @mutex is unlocked before
686 * falling asleep and locked again before resuming.
688 * If @abs_time is %NULL, g_cond_timed_wait() acts like g_cond_wait().
690 * This function can be used even if g_thread_init() has not yet been
691 * called, and, in that case, will immediately return %TRUE.
693 * To easily calculate @abs_time a combination of g_get_current_time()
694 * and g_time_val_add() can be used.
696 * Returns: %TRUE if @cond was signalled, or %FALSE on timeout
699 g_cond_timed_wait (GCond *cond,
703 struct timespec end_time;
706 if (abs_time == NULL)
708 g_cond_wait (cond, mutex);
712 end_time.tv_sec = abs_time->tv_sec;
713 end_time.tv_nsec = abs_time->tv_usec * 1000;
715 if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
718 if G_UNLIKELY (status != ETIMEDOUT)
719 g_thread_abort (status, "pthread_cond_timedwait");
727 * @mutex: a #GMutex that is currently locked
728 * @abs_time: the final time, in microseconds
730 * A variant of g_cond_timed_wait() that takes @abs_time
731 * as a #gint64 instead of a #GTimeVal.
732 * See g_cond_timed_wait() for details.
734 * Returns: %TRUE if @cond was signalled, or %FALSE on timeout
739 g_cond_timedwait (GCond *cond,
743 struct timespec end_time;
746 end_time.tv_sec = abs_time / 1000000;
747 end_time.tv_nsec = (abs_time % 1000000) * 1000;
749 if ((status = pthread_cond_timedwait (&cond->impl, &mutex->impl, &end_time)) == 0)
752 if G_UNLIKELY (status != ETIMEDOUT)
753 g_thread_abort (status, "pthread_cond_timedwait");
761 g_private_init (GPrivate *key,
762 GDestroyNotify notify)
764 pthread_key_create (&key->key, notify);
770 * @private_key: a #GPrivate
772 * Returns the pointer keyed to @private_key for the current thread. If
773 * g_private_set() hasn't been called for the current @private_key and
774 * thread yet, this pointer will be %NULL.
776 * This function can be used even if g_thread_init() has not yet been
777 * called, and, in that case, will return the value of @private_key
778 * casted to #gpointer. Note however, that private data set
779 * <emphasis>before</emphasis> g_thread_init() will
780 * <emphasis>not</emphasis> be retained <emphasis>after</emphasis> the
781 * call. Instead, %NULL will be returned in all threads directly after
782 * g_thread_init(), regardless of any g_private_set() calls issued
783 * before threading system initialization.
785 * Returns: the corresponding pointer
788 g_private_get (GPrivate *key)
791 return key->single_value;
793 /* quote POSIX: No errors are returned from pthread_getspecific(). */
794 return pthread_getspecific (key->key);
799 * @private_key: a #GPrivate
800 * @data: the new pointer
802 * Sets the pointer keyed to @private_key for the current thread.
804 * This function can be used even if g_thread_init() has not yet been
805 * called, and, in that case, will set @private_key to @data casted to
806 * #GPrivate*. See g_private_get() for resulting caveats.
809 g_private_set (GPrivate *key,
816 key->single_value = value;
820 if G_UNLIKELY ((status = pthread_setspecific (key->key, value)) != 0)
821 g_thread_abort (status, "pthread_setspecific");
826 #define posix_check_err(err, name) G_STMT_START{ \
829 g_error ("file %s: line %d (%s): error '%s' during '%s'", \
830 __FILE__, __LINE__, G_STRFUNC, \
831 g_strerror (error), name); \
834 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
837 g_system_thread_create (GThreadFunc thread_func,
847 g_return_if_fail (thread_func);
849 posix_check_cmd (pthread_attr_init (&attr));
851 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
854 #ifdef _SC_THREAD_STACK_MIN
855 stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), stack_size);
856 #endif /* _SC_THREAD_STACK_MIN */
857 /* No error check here, because some systems can't do it and
858 * we simply don't want threads to fail because of that. */
859 pthread_attr_setstacksize (&attr, stack_size);
861 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
863 posix_check_cmd (pthread_attr_setdetachstate (&attr,
864 joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
866 ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
868 posix_check_cmd (pthread_attr_destroy (&attr));
872 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
873 "Error creating thread: %s", g_strerror (ret));
877 posix_check_err (ret, "pthread_create");
883 * Gives way to other threads waiting to be scheduled.
885 * This function is often used as a method to make busy wait less evil.
886 * But in most cases you will encounter, there are better methods to do
887 * that. So in general you shouldn't use this function.
890 g_thread_yield (void)
896 g_system_thread_join (gpointer thread)
899 posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
903 g_system_thread_exit (void)
909 g_system_thread_self (gpointer thread)
911 *(pthread_t*)thread = pthread_self();
915 g_system_thread_equal (gpointer thread1,
918 return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
922 /* vim:set foldmethod=marker: */