使用 C++11 标准库中的 std::thread、std::mutex、std::condition_variable、std::function 和 std::queue 等组件实现。
#include<iostream>
using namespace std;
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>class ThreadPool//定义了一个 ThreadPool 类
{
public:ThreadPool(int numThreads) : stop(false) {for (int i = 0; i < numThreads; i++){threads.emplace_back([this] {//加线程while (true){unique_lock<mutex>lock(mt);//任务为空时阻塞condition.wait(lock, [this] {return stop || !tasks.empty(); });//任务不为空或线程停止时不阻塞if (stop && tasks.empty()){return;}function<void()>task(move(tasks.front()));//取任务tasks.pop();lock.unlock();task();//完成任务}});}}~ThreadPool() {{unique_lock<mutex>lock(mt);stop = true;}condition.notify_all();for (thread& thread : threads) {thread.join();}}template<typename F,typename... Args>void enqueue(F&& f, Args&&... args) {//模版内的右值引用为万能引用function<void()>task(bind(forward<F>(f), forward<Args>(args)...));{unique_lock<mutex>lock(mt);tasks.emplace(move(task));}condition.notify_one();}private:vector<thread>threads;queue<function<void()>>tasks;mutex mt;condition_variable condition;bool stop;
};int main()
{ThreadPool pool(4);for (int i = 0; i < 8; i++){pool.enqueue([i] {cout << "task " << i << "is running in thread" << this_thread::get_id() << endl;this_thread::sleep_for(chrono::seconds(1));cout << "Task" << i << "is done" << endl;});}system("pause");system("cls");
}