3 #ifndef __CPPUNIT_THREAD_H
4 #define __CPPUNIT_THREAD_H
6 #include <cds/details/defs.h>
7 #include "cppunit/cppunit_mini.h"
8 #include <boost/thread.hpp>
9 #include <cds/os/timer.h>
10 #include <cds/threading/model.h> // for attach/detach thread
11 #include <cds/algo/atomic.h>
13 namespace CppUnitMini {
14 static inline unsigned int Rand( unsigned int nMax )
16 double rnd = double( rand() ) / double( RAND_MAX );
17 unsigned int n = (unsigned int) (rnd * nMax);
18 return n < nMax ? n : (n-1);
25 typedef TestThread Base;
26 friend class ThreadPool;
29 boost::thread * m_pThread;
30 cds::OS::Timer m_Timer;
31 atomics::atomic<bool> m_bTimeElapsed;
38 static void threadEntryPoint( TestThread * pThread );
40 TestThread( TestThread& src )
41 : m_Pool( src.m_Pool )
42 , m_pThread( nullptr )
43 , m_bTimeElapsed( false )
54 virtual TestThread * clone() = 0;
59 virtual void init() {}
60 virtual void test() = 0;
61 virtual void fini() {}
64 m_bTimeElapsed.store( true, atomics::memory_order_release );
66 bool time_elapsed() const
68 return m_bTimeElapsed.load( atomics::memory_order_acquire );
71 bool check_timeout( size_t nMaxDuration )
73 return m_Timer.duration() > nMaxDuration;
76 void error(const char *in_macroName, const char *in_macro, const char *in_file, int in_line);
79 TestThread( ThreadPool& pool )
81 , m_pThread( nullptr )
93 typedef std::vector< TestThread * > thread_vector;
95 boost::thread_group m_Pool;
96 thread_vector m_arrThreads;
98 boost::barrier * volatile m_pBarrierStart;
99 boost::barrier * volatile m_pBarrierDone;
102 typedef thread_vector::iterator iterator;
105 ThreadPool( TestCase& tc )
107 , m_pBarrierStart( nullptr )
108 , m_pBarrierDone( nullptr )
112 void add( TestThread * pThread, size_t nCount );
115 void run( unsigned int nDuration );
117 void onThreadInitDone( TestThread * pThread );
118 void onThreadTestDone( TestThread * pThread );
119 void onThreadFiniDone( TestThread * pThread );
121 iterator begin() { return m_arrThreads.begin(); }
122 iterator end() { return m_arrThreads.end() ; }
124 double avgDuration() const
127 for ( size_t i = 0; i < m_arrThreads.size(); ++i )
128 nDur += m_arrThreads[i]->m_nDuration;
129 return nDur / m_arrThreads.size();
134 #endif // #ifndef __CPPUNIT_THREAD_H