#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back([this] {
while (true) {
unique_lock<mutex> lock(mtx);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
function<void()> task(move(tasks.front()));
tasks.pop();
lock.unlock();
task();
}
});
}
}
~ThreadPool() {
{
unique_lock<mutex> lock(mtx);
stop = true;
}
condition.notify_all();
for (thread& thread : threads) {
thread.join();
}
}
template<typename F, typename... Args>
void enqueue(F&& f, Args&&... args) {
function<void()> task(bind(forward<F>(f), forward<Args>(args)...));
{
unique_lock<mutex> lock(mtx);
tasks.emplace(move(task));
}
condition.notify_one();
}
private:
vector<thread> threads;
queue<function<void()>> tasks;
mutex mtx;
condition_variable condition;
bool stop;
};
int main() {
ThreadPool pool(4);
for (int i = 0; i < 10; ++i) {
pool.enqueue([i] {
cout << "Task " << i << " is running in thread " << this_thread::get_id() << endl;
this_thread::sleep_for(chrono::seconds(1));
cout << "Task " << i << " is done" << endl;
});
}
return 0;
}
多线程之C++11跨平台线程池
最新推荐文章于 2024-08-09 10:25:03 发布
本文详细介绍了如何使用C++实现一个简单的线程池,包括线程的创建、任务的队列管理和停止条件的控制。通过`std::thread`,`std::mutex`,和`std::condition_variable`实现了高效的并发处理。
摘要由CSDN通过智能技术生成