LogSystem beta 1.4
This is a logging system project
 
载入中...
搜索中...
未找到
threadpool.hpp
浏览该文件的文档.
1
3#pragma once
4#include <iostream>
5#include <functional>
6#include <memory>
7#include <thread>
8#include <future>
9#include <mutex>
10#include <vector>
11#include <condition_variable>
12#include <atomic>
13#include "../logs/Xulog.h"
14
15namespace XuServer
16{
20 {
21 public:
22 using ptr = std::unique_ptr<threadpool>;
23 using Functor = std::function<void(void)>;
24
27 threadpool(int thr_count = 1) : _stop(false)
28 {
29 for (int i = 0; i < thr_count; i++)
30 _threads.emplace_back(&threadpool::entry, this);
31 }
34 {
35 stop();
36 }
38 void stop()
39 {
40 if (_stop == true)
41 return;
42 _stop = true;
43 _cv.notify_all(); // 唤醒线程
44 for (auto &thread : _threads)
45 thread.join();
46 }
47
54 template <typename F, typename... Args>
55 auto push(F &&func, Args &&...args) -> std::future<decltype(func(args...))>
56 {
57 // 将传入函数封装成packaged_task任务包
58 using return_type = decltype(func(args...));
59 auto tmp_func = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
60 auto task = std::make_shared<std::packaged_task<return_type()>>(tmp_func);
61 std::future<return_type> fu = task->get_future();
62 // 构造lambda表达式(捕获任务对象,函数内执行任务对象)
63 {
64 std::unique_lock<std::mutex> lock(_mutex);
65 // 将构造出来的匿名对象传入任务池
66 _taskpool.push_back([task]()
67 { (*task)(); });
68 _cv.notify_one();
69 }
70 return fu;
71 }
72
73 private:
75 void entry()
76 {
77 while (!_stop)
78 {
79 // 临时任务池
80 // 避免频繁加解锁
81 std::vector<Functor> tmp_taskpool;
82 {
83 // 加锁
84 std::unique_lock<std::mutex> lock(_mutex);
85 // 等待任务不为空或_stop被置为1
86 _cv.wait(lock, [this]()
87 { return _stop || !_taskpool.empty(); });
88
89 // 取出任务进行执行
90 tmp_taskpool.swap(_taskpool);
91 }
92 for (auto &task : tmp_taskpool)
93 {
94 task();
95 }
96 }
97 }
98
99 private:
100 std::atomic<bool> _stop;
101 std::vector<Functor> _taskpool;
102 std::mutex _mutex;
103 std::condition_variable _cv;
104 std::vector<std::thread> _threads;
105 };
106}
线程池类
Definition threadpool.hpp:20
std::vector< std::thread > _threads
管理线程
Definition threadpool.hpp:104
threadpool(int thr_count=1)
构造函数
Definition threadpool.hpp:27
std::vector< Functor > _taskpool
任务池
Definition threadpool.hpp:101
std::unique_ptr< threadpool > ptr
线程池操作句柄
Definition threadpool.hpp:22
void entry()
线程入口函数 从任务池中取出任务执行
Definition threadpool.hpp:75
std::function< void(void)> Functor
线程池回调函数
Definition threadpool.hpp:23
std::condition_variable _cv
条件变量
Definition threadpool.hpp:103
std::atomic< bool > _stop
原子类型的停止标志
Definition threadpool.hpp:100
void stop()
停止所有线程
Definition threadpool.hpp:38
auto push(F &&func, Args &&...args) -> std::future< decltype(func(args...))>
传入任务函数到任务池
Definition threadpool.hpp:55
~threadpool()
析构函数
Definition threadpool.hpp:33
std::mutex _mutex
互斥锁
Definition threadpool.hpp:102
Definition config.hpp:9