使用c++11 实现一个简单的线程池

编程入门 行业动态 更新时间:2024-10-26 10:40:29

使用c++11 实现一个简单的<a href=https://www.elefans.com/category/jswz/34/1771240.html style=线程池"/>

使用c++11 实现一个简单的线程池

说明:这里面使用了c++ 新特性:可变参数模版,lambda 表达式,互斥锁,c++11 库的多线程等,function 包装器,完美准发等等知识,可以参考一下内容。每个问题都有详细得说明。

C++ 11 新特性(一)_cat_fish_rain的博客-CSDN博客

C++ 11新特性(二)-CSDN博客

C++ 11 (三)-CSDN博客

#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <thread>
#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([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 = std::move(tasks.front());tasks.pop();}task();} });}}template <class F, class... Args>void enqueue(F &&f, Args &&...args){{std::unique_lock<std::mutex> lock(queueMutex);tasks.emplace([&]{ f(args...); });}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;
};// 示例任务函数
void taskFunction(int id)
{std::cout << "Task " << id << " is being processed." << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "Task " << id << " is done." << std::endl;
}int main()
{ThreadPool pool(4); // 创建一个拥有4个线程的线程池// 向线程池中添加任务for (int i = 0; i < 8; ++i){pool.enqueue(taskFunction, i);}// 等待所有任务完成std::this_thread::sleep_for(std::chrono::seconds(5));system("pause");return 0;
}

分析: 

hreadPool类的构造函数接受一个参数numThreads,表示线程池中的线程数量。在构造函数中,通过一个循环创建了numThreads个线程,并将它们存储在workers向量中。

每个线程的执行函数是一个lambda表达式,它会不断地从任务队列中取出任务并执行。在每次循环中,线程会先获取一个互斥锁queueMutex,然后调用条件变量condition的wait函数等待条件满足。条件满足的条件是stop为true或者任务队列不为空。如果stop为true且任务队列为空,线程会退出循环,结束执行。否则,线程会取出任务队列的头部任务,并执行该任务。执行完任务后,线程会继续下一次循环。

ThreadPool类还提供了一个enqueue函数,用于向任务队列中添加任务。enqueue函数接受一个可调用对象f和其参数args。在enqueue函数中,首先获取互斥锁queueMutex,然后将一个lambda表达式封装了f和args,并将该lambda表达式添加到任务队列中。最后,通过条件变量condition的notify_one函数通知一个等待的线程有新任务可执行。

ThreadPool类的析构函数首先设置stop为true,然后通过条件变量condition的notify_all函数通知所有等待的线程停止执行。最后,使用join函数等待所有线程执行完毕。

在main函数中,首先创建了一个拥有4个线程的线程池pool。然后,通过一个循环向线程池中添加了8个任务,每个任务都是调用taskFunction函数,并传入一个不同的id参数。接着,通过std::this_thread::sleep_for函数等待所有任务完成。最后,使用system函数暂停程序的执行,以便在控制台中查看输出结果。

更多推荐

使用c++11 实现一个简单的线程池

本文发布于:2023-11-15 22:41:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!