#include #include #include #include #include #include using namespace std; // Compile with: g++ -g -lboost_thread mt_test.cpp struct ThreadData { ThreadData(const vector& vOne, const double factor) : m_vOne(vOne), m_factor(factor), m_vTwo(vOne.size(), m_factor) { // empty } const vector& m_vOne; double m_factor; vector m_vTwo; }; static void* doAdd(void* data) { ThreadData* pData = static_cast(data); for(unsigned int nAt = 0; nAt < pData->m_vOne.size(); ++nAt) pData->m_vTwo[nAt] += pData->m_factor * pData->m_vOne[nAt]; return NULL; } int main(void) { const int nThreads = 12; const int nRepetitions = 200; vector vOne(1<<24, 1.0); for(int nAtRepetition = 0; nAtRepetition < nRepetitions; ++nAtRepetition) { cout << "Repetition no. " << nAtRepetition << endl; vector vpData(nThreads, static_cast(NULL)); boost::thread_group threads; for (int nAtThread = 0; nAtThread < nThreads; nAtThread++) { vpData[nAtThread] = new ThreadData(vOne, static_cast(nAtThread+1) ); if( threads.create_thread( boost::bind(&doAdd, static_cast (vpData[nAtThread])) ) == 0 ) throw std::exception(); } threads.join_all(); for (int nAtThread = 0; nAtThread < nThreads; nAtThread++) delete vpData[nAtThread]; } return 0; }