C++中如何实现进程池
导读:在C++中可以使用多线程库来实现进程池,以下是一个简单的进程池实现示例: #include <iostream> #include <vector> #include <thread> #include...
在C++中可以使用多线程库来实现进程池,以下是一个简单的进程池实现示例:
#include <
iostream>
#include <
vector>
#include <
thread>
#include <
mutex>
#include <
condition_variable>
#include <
queue>
#include <
functional>
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0;
i <
numThreads;
++i) {
workers.emplace_back([this] {
while (true) {
std::function<
void()>
task;
{
std::unique_lock<
std::mutex>
lock(queueMutex);
condition.wait(lock, [this] {
return stop || !tasks.empty();
}
);
if (stop &
&
tasks.empty()) {
return;
}
task = tasks.front();
tasks.pop();
}
task();
}
}
);
}
}
template<
class F>
void enqueue(F&
&
f) {
{
std::unique_lock<
std::mutex>
lock(queueMutex);
tasks.emplace(std::forward<
F>
(f));
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<
std::mutex>
lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread &
worker : workers) {
worker.join();
}
}
private:
std::vector<
std::thread>
workers;
std::queue<
std::function<
void()>
>
tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
}
;
int main() {
ThreadPool pool(4);
for (int i = 0;
i <
8;
++i) {
pool.enqueue([i] {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout <
<
"Task " <
<
i <
<
" completed" <
<
std::endl;
}
);
}
return 0;
}
在上面的示例中,通过创建一个ThreadPool类来实现进程池,其中包含了一个线程池的构造函数、任务入队函数enqueue和析构函数。可以通过调用enqueue函数向进程池中添加任务,进程池会自动分配线程来执行这些任务。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C++中如何实现进程池
本文地址: https://pptw.com/jishu/695745.html
