#pragma once ///////////////////////////////////////////////////////////////////// // ThreadPool.h - Enqueue work items to run on one of a collection // // of threads, created at startup. // // ver 1.1 // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2016 // ///////////////////////////////////////////////////////////////////// /* * Threadpool is a class that runs work items, each on one of a finite * set of threads managed by the class. Each instance shares a mutex * used to synchronize access to data shared between threads. * * Each thread deQs workItems from a blocking queue of callable objects, * executes the callable object, and goes back to the queue for another. * These workItems must take no arguments and return a bool. The value * of the bool should always be true unless the user wants to shut down * the threadpool. If a job needs input parameters, they are simply * included in the callable object's capture list (lambda) or as member * data (functor). * * The thread pool can be shut down by enqueuing a work item that returns * false. Each thread executes the work item and if false enqueues the * same workItem and then exits. This means that each thread will terminate. * * Required Files: * Threadpool.h, Threadpool.cpp * * Maintenance History: * ver 1.1 : 28 Jul 2016 * - converted from template class to non-template class * ver 1.0 : 04 Apr 2016 * - first release * * ToDo: * - Provide a longRunningOperation option that starts another thread * and terminates when long running operation completes. */ #include #include #include #include #include #include "../Cpp11-BlockingQueue/Cpp11-BlockingQueue.h" #include "../Logger/Logger.h" #include "../Utilities/Utilities.h" namespace Async { class ThreadPool { public: using CallObj = std::function; ThreadPool() {} ThreadPool(const ThreadPool&) = delete; ThreadPool& operator=(const ThreadPool&) = delete; void start(size_t numThrds); void workItem(CallObj& co); void wait(); size_t size(); std::mutex& mutex(); ~ThreadPool(); private: size_t numThrds_; BlockingQueue Q_; std::vector threads_; std::mutex mtx_; // lock shared by all threads in pool std::function threadProc_; }; inline size_t ThreadPool::size() { return numThrds_; } inline std::mutex& ThreadPool::mutex() { return mtx_; } }