Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions CcpSemaphore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ CcpSemaphore::~CcpSemaphore()
}

#include <errno.h>
#include <time.h>

bool CcpSemaphore::Wait()
{
Expand All @@ -110,8 +111,19 @@ bool CcpSemaphore::Wait()
bool CcpSemaphore::TimedWait( uint32_t timeoutInMs )
{
timespec ts;
ts.tv_sec = timeoutInMs / 1000;
ts.tv_nsec = (timeoutInMs % 1000) * 1000000;
if( clock_gettime( CLOCK_REALTIME, &ts ) != 0 )
{
return false;
}

ts.tv_sec += timeoutInMs / 1000;
ts.tv_nsec += static_cast<long>( timeoutInMs % 1000 ) * 1000000L;
if( ts.tv_nsec >= 1000000000L )
{
ts.tv_sec += ts.tv_nsec / 1000000000L;
ts.tv_nsec %= 1000000000L;
}

if( sem_timedwait( &m_semaphore, &ts ) == 0 )
{
return true;
Expand Down
42 changes: 42 additions & 0 deletions tests/CcpSemaphore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,45 @@ TEST( CcpSemaphore, CanWaitOnSemaphore )
EXPECT_GT( duration, 200 );
EXPECT_LT( duration, 1000 );
}

TEST( CcpSemaphore, TimedWaitWaitsAndReturnsFalseOnTimeout )
{
CcpSemaphore s;

bool acquired = true;
auto duration = TimeCallInMs( [&] { acquired = s.TimedWait( 500 ); } );

EXPECT_FALSE( acquired );
EXPECT_GT( duration, 250 );
EXPECT_LT( duration, 1500 );
}

TEST( CcpSemaphore, TimedWaitReturnsTrueWhenAlreadySignaled )
{
CcpSemaphore s;
s.Signal();

bool acquired = false;
auto duration = TimeCallInMs( [&] { acquired = s.TimedWait( 1000 ); } );

EXPECT_TRUE( acquired );
EXPECT_LT( duration, 100 );
}

TEST( CcpSemaphore, TimedWaitReturnsTrueWhenSignaledBeforeTimeout )
{
CcpSemaphore s;

auto thread = [&] {
CcpThreadSleep( 200 );
s.Signal();
};
CcpCreateThread( &MakeThread<decltype( thread )>, &thread, CCP_THREAD_PRIORITY_NORMAL );

bool acquired = false;
auto duration = TimeCallInMs( [&] { acquired = s.TimedWait( 2000 ); } );

EXPECT_TRUE( acquired );
EXPECT_GT( duration, 100 );
EXPECT_LT( duration, 1500 );
}