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");
763 * The #GPrivate struct is an opaque data structure to represent a
764 * thread-local data key. It is approximately equivalent to the
765 * <function>pthread_setspecific()</function>/<function>pthread_getspecific()</function>
766 * APIs on POSIX and to
767 * <function>TlsSetValue()</function>/<function>TlsGetValue<()/function> on
770 * If you don't already know why you might want this functionality, then
771 * you probably don't need it.
773 * #GPrivate is a very limited resource (as far as 128 per program,
774 * shared between all libraries). It is also not possible to destroy a
775 * #GPrivate after it has been used. As such, it is only ever acceptable
776 * to use #GPrivate in static scope, and even then sparingly so.
778 * See G_PRIVATE_INIT() for a couple of examples.
780 * The #GPrivate structure should be considered opaque. It should only
781 * be accessed via the <function>g_private_</function> functions.
786 * @notify: a #GDestroyNotify
788 * A macro to assist with the static initialisation of a #GPrivate.
790 * This macro is useful for the case that a #GDestroyNotify function
791 * should be associated the key. This is needed when the key will be
792 * used to point at memory that should be deallocated when the thread
795 * Additionally, the #GDestroyNotify will also be called on the previous
796 * value stored in the key when g_private_replace() is used.
798 * If no #GDestroyNotify is needed, then use of this macro is not
799 * required -- if the #GPrivate is declared in static scope then it will
800 * be properly initialised by default (ie: to all zeros). See the
804 * static GPrivate name_key = G_PRIVATE_INIT (g_free);
806 * // return value should not be freed
808 * get_local_name (void)
810 * return g_private_get (&name_key);
814 * set_local_name (const gchar *name)
816 * g_private_replace (&name_key, g_strdup (name));
820 * static GPrivate count_key; // no free function
823 * get_local_count (void)
825 * return GPOINTER_TO_INT (g_private_get (&count_key));
829 * set_local_count (gint count)
831 * g_private_set (&count_key, GINT_TO_POINTER (count));
838 static pthread_key_t *
839 g_private_impl_new (GDestroyNotify notify)
844 key = malloc (sizeof (pthread_key_t));
845 if G_UNLIKELY (key == NULL)
846 g_thread_abort (errno, "malloc");
847 status = pthread_key_create (key, notify);
848 if G_UNLIKELY (status != 0)
849 g_thread_abort (status, "pthread_key_create");
855 g_private_impl_free (pthread_key_t *key)
859 status = pthread_key_delete (*key);
860 if G_UNLIKELY (status != 0)
861 g_thread_abort (status, "pthread_key_delete");
865 static pthread_key_t *
866 g_private_get_impl (GPrivate *key)
868 pthread_key_t *impl = key->p;
870 if G_UNLIKELY (impl == NULL)
872 impl = g_private_impl_new (key->notify);
873 if (!g_atomic_pointer_compare_and_exchange (&key->p, NULL, impl))
875 g_private_impl_free (impl);
887 * Returns the current value of the thread local variable @key.
889 * If the value has not yet been set in this thread, %NULL is returned.
890 * Values are never copied between threads (when a new thread is
891 * created, for example).
893 * Returns: the thread-local value
896 g_private_get (GPrivate *key)
898 /* quote POSIX: No errors are returned from pthread_getspecific(). */
899 return pthread_getspecific (*g_private_get_impl (key));
905 * @value: the new value
907 * Sets the thread local variable @key to have the value @value in the
910 * This function differs from g_private_replace() in the following way:
911 * the #GDestroyNotify for @key is not called on the old value.
914 g_private_set (GPrivate *key,
919 if G_UNLIKELY ((status = pthread_setspecific (*g_private_get_impl (key), value)) != 0)
920 g_thread_abort (status, "pthread_setspecific");
926 * @value: the new value
928 * Sets the thread local variable @key to have the value @value in the
931 * This function differs from g_private_set() in the following way: if
932 * the previous value was non-%NULL then the #GDestroyNotify handler for
938 g_private_replace (GPrivate *key,
941 pthread_key_t *impl = g_private_get_impl (key);
945 old = pthread_getspecific (*impl);
946 if (old && key->notify)
949 if G_UNLIKELY ((status = pthread_setspecific (*impl, value)) != 0)
950 g_thread_abort (status, "pthread_setspecific");
955 #define posix_check_err(err, name) G_STMT_START{ \
958 g_error ("file %s: line %d (%s): error '%s' during '%s'", \
959 __FILE__, __LINE__, G_STRFUNC, \
960 g_strerror (error), name); \
963 #define posix_check_cmd(cmd) posix_check_err (cmd, #cmd)
966 g_system_thread_create (GThreadFunc thread_func,
976 g_return_if_fail (thread_func);
978 posix_check_cmd (pthread_attr_init (&attr));
980 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
983 #ifdef _SC_THREAD_STACK_MIN
984 stack_size = MAX (sysconf (_SC_THREAD_STACK_MIN), stack_size);
985 #endif /* _SC_THREAD_STACK_MIN */
986 /* No error check here, because some systems can't do it and
987 * we simply don't want threads to fail because of that. */
988 pthread_attr_setstacksize (&attr, stack_size);
990 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
992 posix_check_cmd (pthread_attr_setdetachstate (&attr,
993 joinable ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED));
995 ret = pthread_create (thread, &attr, (void* (*)(void*))thread_func, arg);
997 posix_check_cmd (pthread_attr_destroy (&attr));
1001 g_set_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN,
1002 "Error creating thread: %s", g_strerror (ret));
1006 posix_check_err (ret, "pthread_create");
1012 * Gives way to other threads waiting to be scheduled.
1014 * This function is often used as a method to make busy wait less evil.
1015 * But in most cases you will encounter, there are better methods to do
1016 * that. So in general you shouldn't use this function.
1019 g_thread_yield (void)
1025 g_system_thread_join (gpointer thread)
1028 posix_check_cmd (pthread_join (*(pthread_t*)thread, &ignore));
1032 g_system_thread_exit (void)
1034 pthread_exit (NULL);
1038 g_system_thread_self (gpointer thread)
1040 *(pthread_t*)thread = pthread_self();
1044 g_system_thread_equal (gpointer thread1,
1047 return (pthread_equal (*(pthread_t*)thread1, *(pthread_t*)thread2) != 0);
1051 /* vim:set foldmethod=marker: */