int pthread_mutex_timedlock(pthread_mutex_t *m, const struct timespec *ts) { unsigned long long t, ct; int r; mutex_t *_m; if (!ts) return pthread_mutex_lock(m); r = mutex_ref(m); if (r) return r; /* Try to lock it without waiting */ r = _mutex_trylock (m); if (r != EBUSY) return mutex_unref(m,r); _m = (mutex_t *)*m; if (_m->type != PTHREAD_MUTEX_NORMAL && COND_LOCKED(_m) && COND_OWNER(_m)) return mutex_unref(m,EDEADLK); ct = _pthread_time_in_ms(); t = _pthread_time_in_ms_from_timespec(ts); mutex_unref(m,r); r = pthread_mutex_lock_intern(m, (ct > t ? 0 : (t - ct))); return r; }
int pthread_mutex_timedlock(pthread_mutex_t *m, const struct timespec *ts) { unsigned long long t, ct; #ifndef USE_MUTEX_Mutex int i = 0; #endif int r; if (!ts) return pthread_mutex_lock(m); r = mutex_ref(m); if (r) return r; /* Try to lock it without waiting */ r=_mutex_trylock(m); if (r != EBUSY) return mutex_unref(m,r); mutex_t *_m = (mutex_t *)*m; if (_m->type != PTHREAD_MUTEX_NORMAL && COND_LOCKED(_m) && COND_OWNER(_m)) return mutex_unref(m,EDEADLK); ct = _pthread_time_in_ms(); t = _pthread_time_in_ms_from_timespec(ts); #ifdef USE_MUTEX_Mutex mutex_unref(m,r); r = pthread_mutex_lock_intern(m, (ct > t ? 0 : (t - ct))); #else mutex_unref(m,EDEADLK); while (1) { /* Have we waited long enough? A high count means we busy-waited probably.*/ if (ct >= t) { printf("%d: Timeout after %d times\n",(int)GetCurrentThreadId(), i); return ETIMEDOUT; } if ((i & 1) == 0) Sleep(0); /* waiter that owner gets released. */ /* Try to grab lock */ r = pthread_mutex_trylock(m); if (r != EBUSY) break; /* Get current time */ ct = _pthread_time_in_ms(); i ++; } #endif return r; }
unsigned long long _pthread_rel_time_in_ms(const struct timespec *ts) { unsigned long long t1 = _pthread_time_in_ms_from_timespec(ts); unsigned long long t2 = _pthread_time_in_ms(); /* Prevent underflow */ if (t1 < t2) return 0; return t1 - t2; }
int pthread_rwlock_timedrdlock(pthread_rwlock_t *l, const struct timespec *ts) { unsigned long long ct = _pthread_time_in_ms(); unsigned long long t = _pthread_time_in_ms_from_timespec(ts); pthread_testcancel(); /* Use a busy-loop */ while (1) { /* Try to grab lock */ if (!pthread_rwlock_tryrdlock(l)) return 0; /* Get current time */ ct = _pthread_time_in_ms(); /* Have we waited long enough? */ if (ct > t) return ETIMEDOUT; } }