3 #ifndef __CPPUNIT_THREAD_H
4 #define __CPPUNIT_THREAD_H
6 #include "cppunit/cppunit_mini.h"
7 #include <boost/thread.hpp>
8 #include <cds/os/timer.h>
9 #include <cds/threading/model.h> // for attach/detach thread
10 #include <cds/cxx11_atomic.h>
12 namespace CppUnitMini {
13 static inline unsigned int Rand( unsigned int nMax )
15 double rnd = double( rand() ) / double( RAND_MAX );
16 unsigned int n = (unsigned int) (rnd * nMax);
17 return n < nMax ? n : (n-1);
24 typedef TestThread Base;
25 friend class ThreadPool;
28 boost::thread * m_pThread;
29 cds::OS::Timer m_Timer;
30 CDS_ATOMIC::atomic<bool> m_bTimeElapsed;
37 static void threadEntryPoint( TestThread * pThread );
39 TestThread( TestThread& src )
40 : m_Pool( src.m_Pool )
42 , m_bTimeElapsed( false )
53 virtual TestThread * clone() = 0;
58 virtual void init() {}
59 virtual void test() = 0;
60 virtual void fini() {}
63 m_bTimeElapsed.store( true, CDS_ATOMIC::memory_order_release );
65 bool time_elapsed() const
67 return m_bTimeElapsed.load( CDS_ATOMIC::memory_order_acquire );
70 bool check_timeout( size_t nMaxDuration )
72 return m_Timer.duration() > nMaxDuration;
75 void error(const char *in_macroName, const char *in_macro, const char *in_file, int in_line);
78 TestThread( ThreadPool& pool )
92 typedef std::vector< TestThread * > thread_vector;
94 boost::thread_group m_Pool;
95 thread_vector m_arrThreads;
97 boost::barrier * volatile m_pBarrierStart;
98 boost::barrier * volatile m_pBarrierDone;
101 typedef thread_vector::iterator iterator;
104 ThreadPool( TestCase& tc )
106 , m_pBarrierStart( NULL )
107 , m_pBarrierDone( NULL )
111 void add( TestThread * pThread, size_t nCount );
114 void run( unsigned int nDuration );
116 void onThreadInitDone( TestThread * pThread );
117 void onThreadTestDone( TestThread * pThread );
118 void onThreadFiniDone( TestThread * pThread );
120 iterator begin() { return m_arrThreads.begin(); }
121 iterator end() { return m_arrThreads.end() ; }
123 double avgDuration() const
126 for ( size_t i = 0; i < m_arrThreads.size(); ++i )
127 nDur += m_arrThreads[i]->m_nDuration;
128 return nDur / m_arrThreads.size();
133 #endif // #ifndef __CPPUNIT_THREAD_H