bool tryPop( T& t ) { std::lock_guard<std::mutex> smartLock(m); if(q.empty()) return false; t = std::move( q.front() ); q.pop(); return true; }
void ThreadPool::AddJob(function<void(void)> job){ if(stopped) throw ""; if(quit) throw ""; // Wake up one thread. { std::unique_lock<std::mutex> smartLock(mtx); jobQueue.push(job); cv.notify_one(); } }
void ThreadPool::ShutDown(){ if(!stopped){ // Wake up all threads. { std::unique_lock<std::mutex> smartLock(mtx); quit = true; cv.notify_all(); } for(auto& e : threads) e.join(); threads.clear(); stopped = true; } }
void calcItem(size_t item, bool needLock) { uint64_t itemValue; itemValue = 123; // ... (a lengthy calculation) // 123 to make it compile if(needLock) { // acquire smartLock std::unique_lock<std::mutex> smartLock (vLock); v.push_back(itemValue); } // release smartLock else { v.push_back(itemValue); } }
void ThreadPool::Run(int threadNumber){ std::function<void(void)> job; Timer t; Timer tJob; uint64_t cummulativeTime = 0; uint64_t activeTime = 0; t.Start(); while(true){ { std::unique_lock<std::mutex> smartLock(mtx); auto f = [this] () {return !jobQueue.empty() || quit;}; cv.wait(smartLock,f); if(quit && jobQueue.empty()){ goto Quit; } job=jobQueue.front(); jobQueue.pop(); } tJob.Start(); job(); tJob.Stop(); cummulativeTime += tJob.USecs(); } Quit: t.Stop(); activeTime = t.USecs(); std::stringstream ss; ss << "thread pool thread "<< threadNumber << " was active for " << cummulativeTime << "/" << "microseconds." << 100 * double(cummulativeTime) /double(activeTime) << " busy\n"; std::cout << ss.str(); }
void push( T& t ) { std::lock_guard<std::mutex> smartLock(m); q.push( std::move( t ) ); }
bool empty() const { std::lock_guard<std::mutex> smartLock(m); return q.empty(); }
~tsQueue() { std::lock_guard<std::mutex> smartLock(m); while( ! q.empty() ) q.pop(); }