直接上代码,懂得都懂。
#include
#include
#include
#include
#include
#include class ThreadPool {
public:ThreadPool(size_t threadCount) : m_stop(false) {for (size_t i = 0; i < threadCount; ++i) {m_threads.emplace_back(std::thread(&ThreadPool::worker, this));}}~ThreadPool() {{std::unique_lock lock(m_mutex);m_stop = true;}m_condition.notify_all();for (auto& thread : m_threads) {thread.join();}}templatevoid enqueue(Func&& func, Args&&... args) {auto task = std::make_shared>(std::bind(std::forward(func), std::forward(args)...));{std::unique_lock lock(m_mutex);m_tasks.push(task);}m_condition.notify_one();}private:void worker() {while (true) {std::shared_ptr> task;{std::unique_lock lock(m_mutex);m_condition.wait(lock, [this]() { return !m_tasks.empty() || m_stop; });if (m_stop && m_tasks.empty()) {return;}task = m_tasks.front();m_tasks.pop();}(*task)();}}std::vector m_threads;std::queue>> m_tasks;std::mutex m_mutex;std::condition_variable m_condition;bool m_stop;
};
这个线程池使用了 C++11 的特性,包括 std::thread、std::mutex、std::condition_variable 等,实现了一个可变大小的线程池。
如果你觉得我的文章对你有帮助那边就请收藏和关注我,我会不定期的更新技术文章,谢谢!!!
下一篇:9.数据结构概述