标签:占位符 头部 执行 综合 构造 master expr row 位置
咳咳。C++11 加入了线程库,从此告别了标准库不支持并发的历史。然而 c++ 对于多线程的支持还是比较低级,稍微高级一点的用法都需要自己去实现,譬如线程池、信号量等。线程池(thread pool)这个东西,在面试上多次被问到,一般的回答都是:“管理一个任务队列,一个线程队列,然后每次取一个任务分配给一个线程去做,循环往复。” 貌似没有问题吧。但是写起程序来的时候就出问题了。
废话不多说,先上实现,然后再啰嗦。(dont talk, show me ur code !)
1 #pragma once
2 #ifndef THREAD_POOL_H
3 #define THREAD_POOL_H
4
5 #include <vector>
6 #include <queue>
7 #include <thread>
8 #include <atomic>
9 #include <condition_variable>
10 #include <future>
11 #include <functional>
12 #include <stdexcept>
13
14 namespace std
15 {
16 #define MAX_THREAD_NUM 256
17
18 //线程池,可以提交变参函数或拉姆达表达式的匿名函数执行,可以获取执行返回值
19 //不支持类成员函数, 支持类静态成员函数或全局函数,Opteron()函数等
20 class threadpool
21 {
22 using Task = std::function<void()>;
23 // 线程池
24 std::vector<std::thread> pool;
25 // 任务队列
26 std::queue<Task> tasks;
27 // 同步
28 std::mutex m_lock;
29 // 条件阻塞
30 std::condition_variable cv_task;
31 // 是否关闭提交
32 std::atomic<bool> stoped;
33 //空闲线程数量
34 std::atomic<int> idlThrNum;
35
36 public:
37 inline threadpool(unsigned short size = 4) :stoped{ false }
38 {
39 idlThrNum = size < 1 ? 1 : size;
40 for (size = 0; size < idlThrNum; ++size)
41 { //初始化线程数量
42 pool.emplace_back(
43 [this]
44 { // 工作线程函数
45 for (;;)
46 {
47 std::function<void()> task;
48 { // 获取一个待执行的 task
49 std::unique_lock<std::mutex> lock{ this->m_lock };// unique_lock 相比 lock_guard 的好处是:可以随时 unlock() 和 lock()
50 this->cv_task.wait(lock,
51 [this] {
52 return this->stoped.load() || !this->tasks.empty();
53 }
54 ); // wait 直到有 task
55 if (this->stoped && this->tasks.empty())
56 return;
57 task = std::move(this->tasks.front()); // 取一个 task
58 this->tasks.pop();
59 }
60 idlThrNum--;
61 task();
62 idlThrNum++;
63 }
64 }
65 );
66 }
67 }
68 inline ~threadpool()
69 {
70 stoped.store(true);
71 cv_task.notify_all(); // 唤醒所有线程执行
72 for (std::thread& thread : pool) {
73 //thread.detach(); // 让线程“自生自灭”
74 if(thread.joinable())
75 thread.join(); // 等待任务结束, 前提:线程一定会执行完
76 }
77 }
78
79 public:
80 // 提交一个任务
81 // 调用.get()获取返回值会等待任务执行完,获取返回值
82 // 有两种方法可以实现调用类成员,
83 // 一种是使用 bind: .commit(std::bind(&Dog::sayHello, &dog));
84 // 一种是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog)
85 template<class F, class... Args>
86 auto commit(F&& f, Args&&... args) ->std::future<decltype(f(args...))>
87 {
88 if (stoped.load()) // stop == true ??
89 throw std::runtime_error("commit on ThreadPool is stopped.");
90
91 using RetType = decltype(f(args...)); // typename std::result_of<F(Args...)>::type, 函数 f 的返回值类型
92 auto task = std::make_shared<std::packaged_task<RetType()> >(
93 std::bind(std::forward<F>(f), std::forward<Args>(args)...)
94 ); // wtf !
95 std::future<RetType> future = task->get_future();
96 { // 添加任务到队列
97 std::lock_guard<std::mutex> lock{ m_lock };//对当前块的语句加锁 lock_guard 是 mutex 的 stack 封装类,构造的时候 lock(),析构的时候 unlock()
98 tasks.emplace(
99 [task]()
100 { // push(Task{...})
101 (*task)();
102 }
103 );
104 }
105 cv_task.notify_one(); // 唤醒一个线程执行
106
107 return future;
108 }
109
110 //空闲线程数量
111 int idlCount() { return idlThrNum; }
112
113 };
114
115 }
116
117 #endif
代码不多吧,上百行代码就完成了 线程池, 并且, 看看 commit, 哈, 不是固定参数的, 无参数数量限制! 这得益于可变参数模板.
怎么使用? 看下面代码(展开查看)
1 #include "threadpool.h"
2 #include <iostream>
3
4 void fun1(int slp)
5 {
6 printf(" hello, fun1 ! %d\n" ,std::this_thread::get_id());
7 if (slp>0) {
8 printf(" ======= fun1 sleep %d ========= %d\n",slp, std::this_thread::get_id());
9 std::this_thread::sleep_for(std::chrono::milliseconds(slp));
10 }
11 }
12
13 struct gfun {
14 int operator()(int n) {
15 printf("%d hello, gfun ! %d\n" ,n, std::this_thread::get_id() );
16 return 42;
17 }
18 };
19
20 class A {
21 public:
22 static int Afun(int n = 0) { //函数必须是 static 的才能直接使用线程池
23 std::cout << n << " hello, Afun ! " << std::this_thread::get_id() << std::endl;
24 return n;
25 }
26
27 static std::string Bfun(int n, std::string str, char c) {
28 std::cout << n << " hello, Bfun ! "<< str.c_str() <<" " << (int)c <<" " << std::this_thread::get_id() << std::endl;
29 return str;
30 }
31 };
32
33 int main()
34 try {
35 std::threadpool executor{ 50 };
36 A a;
37 std::future<void> ff = executor.commit(fun1,0);
38 std::future<int> fg = executor.commit(gfun{},0);
39 std::future<int> gg = executor.commit(a.Afun, 9999); //IDE提示错误,但可以编译运行
40 std::future<std::string> gh = executor.commit(A::Bfun, 9998,"mult args", 123);
41 std::future<std::string> fh = executor.commit([]()->std::string { std::cout << "hello, fh ! " << std::this_thread::get_id() << std::endl; return "hello,fh ret !"; });
42
43 std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
44 std::this_thread::sleep_for(std::chrono::microseconds(900));
45
46 for (int i = 0; i < 50; i++) {
47 executor.commit(fun1,i*100 );
48 }
49 std::cout << " ======= commit all ========= " << std::this_thread::get_id()<< " idlsize="<<executor.idlCount() << std::endl;
50
51 std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
52 std::this_thread::sleep_for(std::chrono::seconds(3));
53
54 ff.get(); //调用.get()获取返回值会等待线程执行完,获取返回值
55 std::cout << fg.get() << " " << fh.get().c_str()<< " " << std::this_thread::get_id() << std::endl;
56
57 std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
58 std::this_thread::sleep_for(std::chrono::seconds(3));
59
60 std::cout << " ======= fun1,55 ========= " << std::this_thread::get_id() << std::endl;
61 executor.commit(fun1,55).get(); //调用.get()获取返回值会等待线程执行完
62
63 std::cout << "end... " << std::this_thread::get_id() << std::endl;
64
65
66 std::threadpool pool(4);
67 std::vector< std::future<int> > results;
68
69 for (int i = 0; i < 8; ++i) {
70 results.emplace_back(
71 pool.commit([i] {
72 std::cout << "hello " << i << std::endl;
73 std::this_thread::sleep_for(std::chrono::seconds(1));
74 std::cout << "world " << i << std::endl;
75 return i*i;
76 })
77 );
78 }
79 std::cout << " ======= commit all2 ========= " << std::this_thread::get_id() << std::endl;
80
81 for (auto && result : results)
82 std::cout << result.get() << ‘ ‘;
83 std::cout << std::endl;
84 return 0;
85 }
86 catch (std::exception& e) {
87 std::cout << "some unhappy happened... " << std::this_thread::get_id() << e.what() << std::endl;
88 }
为了避嫌,先进行一下版权说明:代码是 me “写”的,但是思路来自 Internet, 特别是这个线程池实现(基本 copy 了这个实现,加上这位同学的实现和解释,好东西值得 copy ! 然后综合更改了下,更加简洁)。
接着前面的废话说。“管理一个任务队列,一个线程队列,然后每次取一个任务分配给一个线程去做,循环往复。” 这个思路有神马问题?线程池一般要复用线程,所以如果是取一个 task 分配给某一个 thread,执行完之后再重新分配,在语言层面基本都是不支持的:一般语言的 thread 都是执行一个固定的 task 函数,执行完毕线程也就结束了(至少 c++ 是这样)。so 要如何实现 task 和 thread 的分配呢?
让每一个 thread 都去执行调度函数:循环获取一个 task,然后执行之。
idea 是不是很赞!保证了 thread 函数的唯一性,而且复用线程执行 task 。
即使理解了 idea,代码还是需要详细解释一下的。
即使懂原理也不代表能写出程序,上面用了众多c++11的“奇技淫巧”,下面简单描述之。
[copy right from url: http://blog.csdn.net/zdarks/article/details/46994607, https://github.com/progschj/ThreadPool/blob/master/ThreadPool.h]
标签:占位符 头部 执行 综合 构造 master expr row 位置
原文地址:http://www.cnblogs.com/diegodu/p/7050359.html