#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads)
:stop(false)
{
for (size_t i = 0; i < numThreads; ++i)
{
workers.emplace_back(std::bind(&ThreadPool::workerThread, this));
}
}
template <class F>
void enqueue(F f)
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::function<void()>(f));
}
cv.notify_one();
}
~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
cv.notify_all();
for (auto &worker : workers)
{
worker.join();
}
}
private:
void workerThread()
{
while (true)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
cv.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty())
{
return;
}
task = tasks.front();
tasks.pop();
}
task();
}
}
private:
bool stop;
std::mutex queue_mutex;
std::condition_variable cv;
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
};
int main()
{
ThreadPool pool(4);
for (int i = 0; i < 8; ++i)
{
pool.enqueue([i] {
std::cout << "Task " << i << " executed" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
});
}
return 0;
}
C++11 实现线程池
最新推荐文章于 2024-11-07 15:40:17 发布