在C++中可以使用多线程库来实现进程池,以下是一个简单的进程池实现示例:
#include
#include
#include
#include
#include
#include
#include
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function task;
{
std::unique_lock lock(queueMutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = tasks.front();
tasks.pop();
}
task();
}
});
}
}
template
void enqueue(F&& f) {
{
std::unique_lock lock(queueMutex);
tasks.emplace(std::forward(f));
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) {
worker.join();
}
}
private:
std::vector workers;
std::queue> 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函数向进程池中添加任务,进程池会自动分配线程来执行这些任务。