3 #include "cppunit/thread.h"
4 #include <boost/date_time/posix_time/posix_time_types.hpp>
6 namespace CppUnitMini {
8 void TestThread::threadEntryPoint( TestThread * pInst )
13 void TestThread::create()
15 m_pThread = new boost::thread( threadEntryPoint, this );
18 void TestThread::run()
22 m_Pool.onThreadInitDone( this );
25 m_Pool.onThreadTestDone( this );
28 m_Pool.onThreadFiniDone( this );
30 catch ( std::exception& ex )
32 m_Pool.m_Test.message( "EXCEPTION in working thread: ");
33 m_Pool.m_Test.message( ex.what() );
37 void TestThread::error(const char *in_macroName, const char *in_macro, const char *in_file, int in_line)
39 m_Pool.m_Test.error( in_macroName, in_macro, in_file, in_line );
43 ThreadPool::~ThreadPool()
45 if ( m_pBarrierStart )
46 delete m_pBarrierStart;
48 delete m_pBarrierDone;
50 for ( size_t i = 0; i < m_arrThreads.size(); ++i )
51 delete m_arrThreads[i];
52 m_arrThreads.resize( 0 );
55 void ThreadPool::add( TestThread * pThread, size_t nCount )
57 pThread->m_nThreadNo = m_arrThreads.size();
58 m_arrThreads.push_back( pThread );
60 TestThread * p = pThread->clone();
62 p->m_nThreadNo = m_arrThreads.size();
63 m_arrThreads.push_back( p );
68 void ThreadPool::run()
70 const size_t nThreadCount = m_arrThreads.size();
71 m_pBarrierStart = new boost::barrier( (unsigned int) nThreadCount );
72 // nThreadCount threads + current thread
73 m_pBarrierDone = new boost::barrier( (unsigned int) (nThreadCount + 1) );
75 for ( size_t i = 0; i < nThreadCount; ++i )
76 m_arrThreads[i]->create();
78 // Wait while all threads is done
79 m_pBarrierDone->wait();
80 boost::this_thread::sleep(boost::posix_time::milliseconds(500));
83 void ThreadPool::run( unsigned int nDuration )
85 const size_t nThreadCount = m_arrThreads.size();
86 m_pBarrierStart = new boost::barrier( (unsigned int) nThreadCount );
87 m_pBarrierDone = new boost::barrier( (unsigned int) (nThreadCount + 1) );
89 for ( size_t i = 0; i < nThreadCount; ++i )
90 m_arrThreads[i]->create();
92 boost::system_time stEnd( boost::get_system_time() + boost::posix_time::seconds( nDuration ) );
94 boost::this_thread::sleep( stEnd );
95 } while ( boost::get_system_time() < stEnd );
97 for ( size_t i = 0; i < nThreadCount; ++i )
98 m_arrThreads[i]->stop();
100 // Wait while all threads is done
101 m_pBarrierDone->wait();
102 boost::this_thread::sleep(boost::posix_time::milliseconds(500));
105 void ThreadPool::onThreadInitDone( TestThread * pThread )
107 // Calls in context of caller thread
108 // Wait while all threads started
109 m_pBarrierStart->wait();
111 pThread->m_Timer.reset();
114 void ThreadPool::onThreadTestDone( TestThread * pThread )
116 // Calls in context of caller thread
117 pThread->m_nDuration = pThread->m_Timer.duration();
120 void ThreadPool::onThreadFiniDone( TestThread * /*pThread*/ )
122 // Calls in context of caller thread
123 // Wait while all threads done
124 m_pBarrierDone->wait();