- threadPool.h 头文件
#pragma once #include<iostream> #include<stdlib.h> #include<vector> #include<thread> #include<mutex> #include<functional> #include<queue> using namespace std; class ThreadPool { public: typedef function<void()> Task; ThreadPool(); ~ThreadPool(); private: std::vector<std::thread> threads; queue<Task> task; mutex _mutex; condition_variable cond; bool done; bool isEmpty; bool isFull; size_t nthreads; public: void start(int n); void runtask(); void addTask(const Task& f); void finish(); };
- threadPool.cpp
#include "ThreadPool.h" ThreadPool::ThreadPool():isEmpty(true),isFull(false),done(false) { } ThreadPool::~ThreadPool() { } void ThreadPool::start(int n) { (*this).nthreads = n; for (int i = 0; i < n; i++) { threads.push_back(thread(&ThreadPool::runtask, this)); } } void ThreadPool::runtask() { while (!done) { unique_lock<mutex> lk(_mutex); while (isEmpty) { cond.wait(lk); } if (done) break; Task ta; ta = move(task.front()); task.pop(); if (task.empty()) { isEmpty = true; } isFull = false; ta(); cond.notify_one(); } } void ThreadPool::addTask(const Task& f) { if (!done) { unique_lock<mutex> lk(_mutex); while (isFull) { cond.wait(lk); } task.push(f); if (task.size() == nthreads) isFull = true; cout << "Add a task" << endl; isEmpty = false; cond.notify_one(); } } void ThreadPool::finish() { if (!done) { //unique_lock<mutex> lk(_mutex); done = true; cond.notify_all(); for (int i=0;i<nthreads;i++) { threads[i].join(); } } }
- main.cpp
亲测无bug。#include <iostream> #include "ThreadPool.h" void func(int i) { cout << "task finish" << "----------->" << i << endl; } int main() { ThreadPool p; p.start(4); int i = 0; while (i<100) { i++; // this_thread::sleep_for(chrono::milliseconds(1)); auto task = bind(func, i); p.addTask(task); } p.finish(); return 0; }
- main.cpp