From 2ff714c6138da8abb50fd532503fd8d68a18811a Mon Sep 17 00:00:00 2001 From: Rich Felker Date: Mon, 25 Aug 2014 16:38:25 -0400 Subject: spin in sem_[timed]wait before performing futex wait empirically, this increases the maximum rate of wait/post operations between two threads by 20-150 times on machines I tested, including x86 and arm. conceptually, it makes sense to do some spinning because semaphores are intended to be usable as a notification mechanism between threads, not just as locks, and low-latency notification is a valuable property to have. --- src/thread/sem_timedwait.c | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/thread/sem_timedwait.c') diff --git a/src/thread/sem_timedwait.c b/src/thread/sem_timedwait.c index bfcb6dcd..df5f3a6c 100644 --- a/src/thread/sem_timedwait.c +++ b/src/thread/sem_timedwait.c @@ -8,6 +8,11 @@ static void cleanup(void *p) int sem_timedwait(sem_t *restrict sem, const struct timespec *restrict at) { + if (!sem_trywait(sem)) return 0; + + int spins = 100; + while (spins-- && sem->__val[0] <= 0) a_spin(); + while (sem_trywait(sem)) { int r; a_inc(sem->__val+1); -- cgit v1.2.1