Skip to content

Commit 7bb34c9

Browse files
committed
Changed lightweight semaphore to avoid costly sem_timedwait (on Linux) when timeout is 0 (see #210); also fixed error handling in semaphore
1 parent 4cc3bee commit 7bb34c9

2 files changed

Lines changed: 7 additions & 9 deletions

File tree

build/makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ tests: bin/unittests$(EXT) bin/fuzztests$(EXT)
2929

3030
benchmarks: bin/benchmarks$(EXT)
3131

32-
bin/unittests$(EXT): ../concurrentqueue.h ../blockingconcurrentqueue.h ../tests/unittests/unittests.cpp ../tests/unittests/mallocmacro.cpp ../tests/common/simplethread.h ../tests/common/simplethread.cpp ../tests/common/systemtime.h ../tests/common/systemtime.cpp ../tests/corealgos.h ../tests/unittests/minitest.h makefile
32+
bin/unittests$(EXT): ../concurrentqueue.h ../blockingconcurrentqueue.h ../lightweightsemaphore.h ../tests/unittests/unittests.cpp ../tests/unittests/mallocmacro.cpp ../tests/common/simplethread.h ../tests/common/simplethread.cpp ../tests/common/systemtime.h ../tests/common/systemtime.cpp ../tests/corealgos.h ../tests/unittests/minitest.h makefile
3333
test -d bin || mkdir bin
3434
g++ -std=c++11 -Wall -pedantic-errors -Wpedantic -Wconversion $(OPTS) -fno-elide-constructors ../tests/common/simplethread.cpp ../tests/common/systemtime.cpp ../tests/unittests/unittests.cpp -o bin/unittests$(EXT) $(LD_OPTS)
3535

lightweightsemaphore.h

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -274,8 +274,11 @@ class LightweightSemaphore
274274
if (oldCount > 0)
275275
return true;
276276
if (timeout_usecs < 0)
277-
return m_sema.wait();
278-
if (m_sema.timed_wait((std::uint64_t)timeout_usecs))
277+
{
278+
if (m_sema.wait())
279+
return true;
280+
}
281+
if (timeout_usecs > 0 && m_sema.timed_wait((std::uint64_t)timeout_usecs))
279282
return true;
280283
// At this point, we've timed out waiting for the semaphore, but the
281284
// count is still decremented indicating we may still be waiting on
@@ -311,12 +314,7 @@ class LightweightSemaphore
311314
oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
312315
if (oldCount <= 0)
313316
{
314-
if (timeout_usecs < 0)
315-
{
316-
if (!m_sema.wait())
317-
return 0;
318-
}
319-
else if (!m_sema.timed_wait((std::uint64_t)timeout_usecs))
317+
if ((timeout_usecs == 0) || (timeout_usecs < 0 && !m_sema.wait()) || (timeout_usecs > 0 && !m_sema.timed_wait((std::uint64_t)timeout_usecs)))
320318
{
321319
while (true)
322320
{

0 commit comments

Comments
 (0)