├── ThreadPool.hpp └── main.cpp /ThreadPool.hpp: -------------------------------------------------------------------------------- 1 | // 2 | // ThreadPool.hpp 3 | // Simple Thread Pool 4 | // 5 | // Created by Julien Karst on 01/02/2017. 6 | // Copyright © 2017 Julien Karst. All rights reserved. 7 | // 8 | 9 | #ifndef ThreadPool_hpp 10 | #define ThreadPool_hpp 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | class ThreadPool { 21 | private: 22 | int _nbThreads; 23 | std::vector _pool; 24 | std::condition_variable _cond; 25 | std::mutex _mutex; 26 | std::queue> _queue; 27 | bool _run; 28 | 29 | void addThreads() { 30 | for(int ii = 0; ii < _nbThreads; ii++) { 31 | _pool.push_back(std::thread(&ThreadPool::run, this)); 32 | } 33 | }; 34 | public: 35 | ThreadPool(int nbThreads) : _nbThreads(nbThreads), _run(true) { addThreads(); }; 36 | 37 | ThreadPool() : _nbThreads(std::thread::hardware_concurrency()), _run(false) { addThreads(); }; 38 | 39 | void run() { 40 | std::function task; 41 | while (true) { 42 | { 43 | std::unique_lock lock(_mutex); 44 | 45 | _cond.wait(lock, [this] { 46 | return !this->_queue.empty(); 47 | }); 48 | 49 | task = _queue.front(); 50 | _queue.pop(); 51 | } 52 | task(); 53 | if (_run == false) { return; } 54 | } 55 | }; 56 | 57 | void add(std::function task) { 58 | { 59 | std::unique_lock lock(_mutex); 60 | _queue.push(task); 61 | } 62 | _cond.notify_one(); 63 | }; 64 | 65 | ~ThreadPool() { 66 | { 67 | std::unique_lock lock(_mutex); 68 | _run = false; 69 | } 70 | _cond.notify_all(); 71 | for(std::thread &t : _pool) t.join(); 72 | }; 73 | }; 74 | 75 | #endif /* ThreadPool_hpp */ 76 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "ThreadPool.hpp" 5 | 6 | void func() { 7 | std::this_thread::sleep_for(std::chrono::milliseconds(3000)); 8 | std::cout << "I'm a simple thread" << std::endl; 9 | } 10 | 11 | int main(int argc, const char * argv[]) { 12 | ThreadPool pool; 13 | 14 | pool.add(&func); 15 | pool.add(&func); 16 | pool.add(&func); 17 | pool.add(&func); 18 | std::cout << "I'm the main thread" << std::endl; 19 | return 0; 20 | } 21 | --------------------------------------------------------------------------------