Merge branch 'master' into scmaster
[nova-tt.git] / testsuite / semaphore_test.cpp
blobc91504b3fefed4b3c4b92273ad375ae24c9f2d1c
1 #define BOOST_TEST_MAIN
2 #include <boost/test/included/unit_test.hpp>
4 #include "semaphore.hpp"
6 #include <boost/thread/thread.hpp>
8 using namespace nova;
9 using namespace boost;
11 inline timespec ptime_to_timespec (const boost::posix_time::ptime &tm)
13 const boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));
14 boost::posix_time::time_duration duration (tm - epoch);
15 timespec ts;
16 ts.tv_sec = duration.total_seconds();
17 ts.tv_nsec = duration.total_nanoseconds() % 1000000000;
18 return ts;
22 BOOST_AUTO_TEST_CASE( sem_timed_wait )
24 timed_semaphore sem;
26 system_time const timeout = get_system_time() + posix_time::milliseconds(500);
28 struct timespec timeoutspec = ptime_to_timespec(timeout);
29 int status = sem.timed_wait(timeoutspec);
30 BOOST_REQUIRE(!status);
34 namespace
36 const int thread_count = 8;
37 const int iterations_per_thread = 100000;
39 int count = 0;
41 semaphore s(1);
43 void test_fn(void)
45 for (int i = 0; i != iterations_per_thread; ++i) {
46 s.wait();
47 ++count;
48 s.post();
54 BOOST_AUTO_TEST_CASE( sem_test )
56 thread_group g;
58 for (int i = 0; i != thread_count; ++i)
59 g.create_thread(test_fn);
60 g.join_all();
62 BOOST_REQUIRE_EQUAL(count, iterations_per_thread * thread_count);
65 BOOST_AUTO_TEST_CASE( sem_sync_test )
67 semaphore sem(0);
68 sem.post();
69 semaphore_sync<semaphore> sync(sem);