#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>
class ThreadPool
{
public:
ThreadPool(int numThreads) : stop(false)
{
for (int i = 0; i < numThreads; i++)
{
threads.emplace_back
(
[this]()
{
while (1)
{
std::unique_lock<std::mutex> lock(mux);
condition.wait
(lock,
[this]()
{
return !tasks.empty() || stop;
}
);
if (stop && tasks.empty()) { return; }
std::function<void()> task(std::move(tasks.front()));
tasks.pop();
lock.unlock();
task();
}
}
);
}
}
~ThreadPool()
{
{ //指定锁的范围
std::unique_lock<std::mutex> lock(mux);
stop = true;
}
condition.notify_all();
for (auto& t : threads)
{
t.join();
}
}
template<class F, class... Args>
void enqueue(F &&f, Args&&... args)
{
std::function<void()> task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
{ //指定锁的范围
std::unique_lock<std::mutex> lock(mux);
tasks.emplace(std::move(task));
}
condition.notify_one();
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex mux;
std::condition_variable condition;
bool stop;
};
int main()
{
ThreadPool pool(4);
for (int i = 0; i < 10; i++)
{
pool.enqueue
(
[i]()
{
std::cout << "task:" << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
);
}
}
c++线程池
最新推荐文章于 2025-12-21 00:03:36 发布
博客涉及C++开发语言,但具体内容缺失。C++是重要的后端开发语言,在众多领域有广泛应用。
992

被折叠的 条评论
为什么被折叠?



