Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class threadPool{
- public:
- explicit threadPool(int n) : run(true) {
- assert(n > 1 && n < 16, "number of thread");
- for (int i = 0; i < n; i++) {
- threads.emplace_back(std::thread([this] {
- while (run) {
- std::unique_lock<std::mutex> lock(mtx);
- cond.wait(lock, [this] {return !tasks.empty() && run; });
- while (!tasks.empty()) {
- auto task = std::move(tasks.front());
- task();
- tasks.pop();
- }
- }
- }));
- }
- }
- ~threadPool() {
- stop();
- }
- template <typename Func, class... Args>
- std::future<typename std::result_of<Func(Args...)>::type> add(Func&& func, Args&&... args) {
- typedef typename std::result_of<Func(Args...)>::type return_type;
- if (run) {
- std::lock_guard<std::mutex> lock(mtx);
- auto t = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
- auto ret = t->get_future();
- tasks.emplace([t] {
- (*t)();
- });
- cond.notify_one();
- return std::move(ret);
- }
- }
- void stop() {
- for (std::thread &thread : threads) {
- thread.join();
- }
- cond.notify_all();
- run = false;
- }
- private:
- bool run;
- std::mutex mtx;
- std::condition_variable cond;
- std::vector<std::thread> threads;
- std::queue<std::function<void()>> tasks;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement