//g++ -std=c++11 thread-pool.cpp -lpthread #include #include #include #include #include #include #include #include #include using namespace std; /// \brief Use this class to run tasks in parallel. class ThreadPool { public: ThreadPool(); ThreadPool( size_t threads ); ~ThreadPool(); /// \brief Initialize the ThreadPool with a number of threads. /// This method does nothing if the thread pool is already running, /// i.e. ThreadPool( size_t ) was called. void initializeWithThreads( size_t threads ); /// \brief Schedule a task to be executed by a thread immediately. void schedule( const function& ); /// \brief a blocking function that waits until the threads have processed all the tasks in the queue. void wait() const; private: vector _workers; queue> _taskQueue; atomic_uint _taskCount; mutex _mutex; condition_variable _condition; atomic_bool _stop; }; ThreadPool::ThreadPool() : _workers(), _taskQueue(), _taskCount( 0u ), _mutex(), _condition(), _stop( false ) {} ThreadPool::ThreadPool( size_t threads ) : ThreadPool() { initializeWithThreads( threads ); } ThreadPool::~ThreadPool() { _stop = true; _condition.notify_all(); for ( thread& w: _workers ) { w.join(); } } void ThreadPool::initializeWithThreads( size_t threads ) { for ( size_t i = 0; i < threads; i++ ) { //each thread executes this lambda _workers.emplace_back( [this]() -> void { while (true) { function task; { //acquire lock unique_lock lock( _mutex ); _condition.wait( lock, [this]() -> bool { return !_taskQueue.empty() || _stop; }); if ( _stop && _taskQueue.empty() ) { return; } task = move( _taskQueue.front() ); _taskQueue.pop(); } //release lock task(); _taskCount--; } //while }); } //for } void ThreadPool::schedule( const function& task ) { unique_lock lock( _mutex ); _taskQueue.push( task ); _taskCount++; _condition.notify_one(); } void ThreadPool::wait() const { while ( _taskCount != 0u ) { this_thread::sleep_for( chrono::microseconds(1) ); } } // Driver Functions void w1(){cout<<"1\n";} void w2(){cout<<"2\n";} void w3(){cout<<"3\n";} void w4(){cout<<"4\n";} int main(){ ThreadPool TP(4); for(int i=0;i<10;i++){ int x=i%4; switch (x){ case 0: TP.schedule(w1); case 1: TP.schedule(w2); case 2: TP.schedule(w3); case 3: TP.schedule(w4); } } return 0; }