#include \n#include \n#include \n#include \n#include \n#include <condition_variable>\n\nclass ThreadPool {\npublic:\n ThreadPool(int numThreads) : stop(false) {\n for (int i = 0; i < numThreads; ++i) {\n threads.emplace_back([this] {\n while (true) {\n std::function<void()> task;\n \n {\n std::unique_lockstd::mutex lock(this->queueMutex);\n this->condition.wait(lock, [this] {\n return this->stop || !this->tasks.empty();\n });\n \n if (this->stop && this->tasks.empty()) {\n return;\n }\n \n task = std::move(this->tasks.front());\n this->tasks.pop();\n }\n \n task();\n }\n });\n }\n }\n \n template<typename F, typename... Args>\n void enqueue(F&& f, Args&&... args) {\n {\n std::unique_lockstd::mutex lock(queueMutex);\n tasks.emplace(std::bind(std::forward(f), std::forward(args)...));\n }\n \n condition.notify_one();\n }\n \n ~ThreadPool() {\n {\n std::unique_lockstd::mutex lock(queueMutex);\n stop = true;\n }\n \n condition.notify_all();\n \n for (std::thread& thread : threads) {\n thread.join();\n }\n }\n \nprivate:\n std::vectorstd::thread threads;\n std::queue<std::function<void()>> tasks;\n std::mutex queueMutex;\n std::condition_variable condition;\n bool stop;\n};\n\nvoid task(int id) {\n std::cout << "Task " << id << " is running." << std::endl;\n}\n\nint main() {\n ThreadPool pool(4);\n \n for (int i = 0; i < 8; ++i) {\n pool.enqueue(task, i);\n }\n \n return 0;\n}\n\n在这个代码中,线程池使用一个队列来存储待执行的任务。线程池的构造函数会创建指定数量的线程,并且每个线程都会不断地从任务队列中取出任务并执行。enqueue()函数用于将任务添加到任务队列中,并通过条件变量通知线程池中的线程有新的任务需要执行。线程池的析构函数会等待所有线程执行完毕后退出。\n\n在main()函数中,我们创建了一个包含4个线程的线程池,并通过enqueue()函数向线程池中添加了8个任务。每个任务都是一个简单的输出语句。


原文地址: https://www.cveoy.top/t/topic/pD7f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录