一个简单的 C++ 线程池实现示例,你可以在此基础上根据自己的需要进行修改和扩展
一个用C++实现的线程池
直接上代码,懂得都懂。
第一
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>
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<std::mutex> lock(m_mutex);
m_stop = true;
}
m_condition.notify_all();
for (auto& thread : m_threads) {
thread.join();
}
}
template<typename Func, typename... Args>
void enqueue(Func&& func, Args&&... args) {
auto task = std::make_shared<std::function<void()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
{
std::unique_lock<std::mutex> lock(m_mutex);
m_tasks.push(task);
}
m_condition.notify_one();
}
private:
void worker() {
while (true) {
std::shared_ptr<std::function<void()>> task;
{
std::unique_lock<std::mutex> 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<std::thread> m_threads;
std::queue<std::shared_ptr<std::function<void()>>> m_tasks;
std::mutex m_mutex;
std::condition_variable m_condition;
bool m_stop;
};
这个线程池使用了 C++11 的特性,包括 std::thread、std::mutex、std::condition_variable 等,实现了一个可变大小的线程池。
使用方法
- 创建一个 ThreadPool 对象,指定线程数量。
- 调用 enqueue 方法将需要执行的任务添加到线程池中。
- 当不再需要线程池时,调用其析构函数。
- enqueue 方法使用了可变参数模板和 std::bind 实现了任务的绑定,可以方便地传递任意数量和类型的参数。如果需要传递引用参数,请使用 std::ref。
- 程序结束时应该调用线程池的析构函数,以确保所有线程都被正确地销毁。
- 任务应该是无状态的,即不依赖于任何全局变量或外部状态。如果有需要,应该使用互斥锁或其他同步机制来确保线程安全。
结束
如果你觉得我的文章对你有帮助那边就请收藏和关注我,我会不定期的更新技术文章,谢谢!!!