thread_pool/pool/ThreadPool.h
2023-04-13 13:04:52 +08:00

57 lines
1.4 KiB
C++

//
// Created by dongl on 23-4-12.
//
#ifndef THREAD_POOL_V2_THREADPOOL_H
#define THREAD_POOL_V2_THREADPOOL_H
#include "TaskQueue.h"
#include <thread>
#include <functional>
#include <future>
class ThreadPool {
protected:
class thread_tasks;
public:
explicit ThreadPool(int n_threads = 4);
template<class F, class... Args>
auto pushTask(F && f, Args &&... args) -> std::future<decltype(f(args...))>;
protected:
TaskQueue<std::function<void()>> m_tasks;
std::vector<std::thread> m_threads;
bool m_shutdown;
std::mutex m_conditional_mutex; // 线程休眠锁互斥变量
std::condition_variable m_conditional_lock; //条件变量
static int preemption_event_num;
};
template<class F, class... Args>
auto ThreadPool::pushTask(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {
std::function<decltype(f(args...))()> function = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
auto task_ptr = std::make_shared<std::packaged_task<decltype(f(args...))()>>(function);
// Warp packaged task into void function
std::function<void()> warpper_func = [task_ptr]()
{
(*task_ptr)();
};
m_tasks.press(warpper_func);
// 唤醒一个等待中的线程
m_conditional_lock.notify_one();
// 返回先前注册的任务指针
return task_ptr->get_future();
}
#endif //THREAD_POOL_V2_THREADPOOL_H