// test.cpp : Defines the entry point for the console application. // #include #include #include #include #include #include #include using namespace std; boost::mutex inputMutex; boost::mutex outputMutex; boost::mutex Thread1Lock; boost::mutex Thread2Lock; boost::mutex Thread3Lock; boost::mutex Thread4Lock; vector Input; vector Output; void ExecuteThread(boost::mutex* pThreadMutex, bool* pThreadExecuting) { for(;;) { int input = 0; bool executing = false; { boost::mutex::scoped_lock inputLock(inputMutex); if (Input.size() != 0) { input = Input.back(); Input.pop_back(); executing = true; } }//input mutex is unlocked { boost::mutex::scoped_lock lock(*pThreadMutex); //lock this thread so that WaitTillDone must wait for this thread to stop its work if (executing == true) { *pThreadExecuting = true; for (int x = 0; x < input; ++x) { float y = x / 100.0f; } boost::mutex::scoped_lock outputLock(outputMutex); Output.push_back(1); *pThreadExecuting = false; } }//thread mutex is unlocked if (executing == false) { boost::xtime time; time.nsec = 1; time.sec = 0; boost::thread::sleep(time); } } }//end ExecuteThread bool WaitTillDone() { int size = 0; for (;;) { { boost::mutex::scoped_lock inputLock(inputMutex); size = Input.size(); } if (size == 0) { //even though there is no queued work, there may be work in progress size = 1; boost::mutex::scoped_lock lock1(Thread1Lock); boost::mutex::scoped_lock lock2(Thread2Lock); boost::mutex::scoped_lock lock3(Thread1Lock); boost::mutex::scoped_lock lock4(Thread2Lock); boost::mutex::scoped_lock inputLock2(inputMutex); boost::mutex::scoped_lock outputLock2(outputMutex); size = Input.size(); } if (size == 0) { return true; } boost::xtime time; time.nsec = 1; time.sec = 0; boost::thread::sleep(time); } return false; }//end WaitTillDone int _tmain() { int const WORK = 10000; //time_t Time; //srand(time(&Time)); for (int x = 0; x < WORK; ++x) { //Input.push_back(rand() % (x+1)); Input.push_back(x); } bool Thread1Executing; bool Thread2Executing; bool Thread3Executing; bool Thread4Executing; boost::thread(boost::bind(&ExecuteThread, &Thread1Lock, &Thread1Executing)); boost::thread(boost::bind(&ExecuteThread, &Thread2Lock, &Thread2Executing)); boost::thread(boost::bind(&ExecuteThread, &Thread3Lock, &Thread3Executing)); boost::thread(boost::bind(&ExecuteThread, &Thread4Lock, &Thread4Executing)); WaitTillDone(); int y = Output.size(); if (y != WORK) { int temp = 0;//breakpoint here } assert(WORK == Output.size()); return 0; }