Ai
1 Star 11 Fork 3

ibc-dabing/ThreadPool-CPP11-async

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
threadpool.h 1.34 KB
一键复制 编辑 原始数据 按行查看 历史
kevin 提交于 2024-07-29 11:12 +08:00 . 添加文件
#pragma once
#include <thread>
#include <mutex>
#include <vector>
#include <queue>
#include <atomic>
#include <functional>
#include <condition_variable>
#include <map>
#include <future>
using namespace std;
// ̳߳
class ThreadPool
{
public:
ThreadPool(int min = 4, int max = thread::hardware_concurrency());
~ThreadPool();
void addTask(function<void()> f);
template<typename F, typename... Args>
auto addTask(F&& f, Args&&... args) -> future<typename result_of<F(Args...)>::type>
{
using returnType = typename result_of<F(Args...)>::type;
auto task = make_shared<packaged_task<returnType()>>(
bind(forward<F>(f), forward<Args>(args)...)
);
future<returnType> res = task->get_future();
{
unique_lock<mutex> lock(m_queueMutex);
m_tasks.emplace([task]() { (*task)(); });
}
m_condition.notify_one();
return res;
}
private:
void manager();
void worker();
private:
thread* m_manager;
map<thread::id, thread> m_workers;
vector<thread::id> m_ids;
int m_minThreads;
int m_maxThreads;
atomic<bool> m_stop;
atomic<int> m_curThreads;
atomic<int> m_idleThreads;
atomic<int> m_exitNumber;
queue<function<void()>> m_tasks;
mutex m_idsMutex;
mutex m_queueMutex;
condition_variable m_condition;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/subingwen/thread-pool-cpp11-async.git
git@gitee.com:subingwen/thread-pool-cpp11-async.git
subingwen
thread-pool-cpp11-async
ThreadPool-CPP11-async
master

搜索帮助