1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
3 * mono-mutex.h: Portability wrappers around POSIX Mutexes
5 * Authors: Jeffrey Stedfast <fejj@ximian.com>
7 * Copyright 2002 Ximian, Inc. (www.ximian.com)
21 #include "mono-mutex.h"
25 #if defined(__APPLE__)
26 #define _DARWIN_C_SOURCE
27 #include <pthread_spis.h>
30 #ifndef HAVE_PTHREAD_MUTEX_TIMEDLOCK
31 /* Android does not implement pthread_mutex_timedlock(), but does provide an
32 * unusual declaration: http://code.google.com/p/android/issues/detail?id=7807
34 #ifdef PLATFORM_ANDROID
37 #define CONST_NEEDED const
40 int pthread_mutex_timedlock (pthread_mutex_t *mutex,
41 CONST_NEEDED struct timespec *timeout);
43 pthread_mutex_timedlock (pthread_mutex_t *mutex, CONST_NEEDED struct timespec *timeout)
45 struct timeval timenow;
46 struct timespec sleepytime;
49 /* This is just to avoid a completely busy wait */
50 sleepytime.tv_sec = 0;
51 sleepytime.tv_nsec = 10000000; /* 10ms */
53 while ((retcode = pthread_mutex_trylock (mutex)) == EBUSY) {
54 gettimeofday (&timenow, NULL);
56 if (timenow.tv_sec >= timeout->tv_sec &&
57 (timenow.tv_usec * 1000) >= timeout->tv_nsec) {
61 nanosleep (&sleepytime, NULL);
66 #endif /* HAVE_PTHREAD_MUTEX_TIMEDLOCK */
70 mono_once (mono_once_t *once, void (*once_init) (void))
74 if (!once->complete) {
75 pthread_cleanup_push ((void(*)(void *))pthread_mutex_unlock,
76 (void *)&once->mutex);
77 thr_ret = pthread_mutex_lock (&once->mutex);
78 g_assert (thr_ret == 0);
80 if (!once->complete) {
82 once->complete = TRUE;
84 thr_ret = pthread_mutex_unlock (&once->mutex);
85 g_assert (thr_ret == 0);
87 pthread_cleanup_pop (0);
96 Returns a recursive mutex that is safe under suspension.
98 A suspension safe mutex means one that can handle this scenario:
111 Say (1) happens before (5) and (5) happens before (2).
112 This means that thread 2 was suspended by the kernel because
113 it's waiting on mutext M.
115 Thread 1 then proceed to suspend thread 2 and unlock/lock the
118 If the kernel implements mutexes with FIFO wait lists, this means
119 that thread 1 will be blocked waiting for thread 2 acquire the lock.
120 Since thread 2 is suspended, we have a deadlock.
122 A suspend safe mutex is an unfair lock but will schedule any runable
123 thread that is waiting for a the lock.
125 This problem was witnessed on OSX in mono/tests/thread-exit.cs.
129 mono_mutex_init_suspend_safe (mono_mutex_t *mutex)
131 #if defined(__APPLE__)
133 pthread_mutexattr_t attr;
135 pthread_mutexattr_init (&attr);
136 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
137 pthread_mutexattr_setpolicy_np (&attr, _PTHREAD_MUTEX_POLICY_FIRSTFIT);
138 res = pthread_mutex_init (mutex, &attr);
139 pthread_mutexattr_destroy (&attr);
143 return mono_mutex_init (mutex);