线程池
线程池概念
线程池字面意思就是一个池子里面有很多线程,在Linux我们将线程装在线程池中,等到有任务需要处理就可以从池子中取出线程进行任务处理。
线程池的应用场景:
有大量的数据请求,需要多执行流并行/并发进行处理。
线程池的优点:
处理任务时从线程池中拿出线程,避免了频繁创造与销毁线程造成的资源成本的浪费。
线程池的限制:
一般线程池的线程的数量都是有限制的,必须综合考虑系统资源。
自主编写线程池
编写思路:
线程池构成:多个线程+任务缓冲队列
将任务传入线程池,并且传入任务的处理方法,即一个函数指针,线程池自动调用线程进行任务处理。
线程池实现
线程池头文件
1#include <cstdio>
2 #include <iostream>
3 #include <queue>
4 #include <stdlib.h>
5 #include <pthread.h>
6
7 typedef void(*handler_t)(int);
8 class ThreadTask {//将待处理数据和处理方法有机结合
9 public:
10 void SetTask(int data, handler_t handler){
11 _data = data;
12 _handler = handler;
13 }
14 void Run() {
15 _handler(_data);
16 }
17 private:
18 int _data;
19 handler_t _handler;
20 };
21
22 #define MAX_THREAD 5
23 class ThreadPool {
24 public:
25 ThreadPool(int max_thr = MAX_THREAD):_thr_max(max_thr){
26 pthread_mutex_init(&_mutex, NULL);
27 pthread_cond_init(&_cond, NULL);
28 for (int i= 0; i< _thr_max; i++) {
29 pthread_t tid;
30 int ret = pthread_create(&tid, NULL, thr_start, this);
31 if (ret != 0) {
32 printf("creat error\n");
33 exit(-1);
34 }
35 }
36 }
37 ~ThreadPool(){
38 pthread_mutex_destroy(&_mutex);
39 pthread_cond_destroy(&_cond);
40 }
41 bool TaskPush(ThreadTask &task){
42 pthread_mutex_lock(&_mutex);
43 _queue.push(task);
44 pthread_mutex_unlock(&_mutex);
45 pthread_cond_broadcast(&_cond);
46 return true;
47 }
48 static void *thr_start(void *arg){
49 ThreadPool *p = (ThreadPool *)arg;
50 while(1){
51 pthread_mutex_lock(&p->_mutex);
52 while(p->_queue.empty()) {
53 pthread_cond_wait(&p->_cond, &p->_mutex);
54 }
55 ThreadTask task;
56 task = p->_queue.front();
57 p->_queue.pop();
58 pthread_mutex_unlock(&p->_mutex);
59 task.Run();
60 }
61 return NULL;
62 }
63 private:
64 int _thr_max;
65 std::queue<ThreadTask> _queue;
66 pthread_mutex_t _mutex;
67 pthread_cond_t _cond;
68 };
主函数:
1 #include "threadpool.hpp"
2 #include <unistd.h>
3
4 //function of solve
5
6 void test_func(int data) {
7 int sec = (data%3)+1;
8 printf("tid:%p solve data %d: sleep %d\n", pthread_self(), data, sec);
9 sleep(sec);
10 }
11
12 void tmp_func(int data) {
13 printf("tid: %p -- temp\n", pthread_self());
14 }
15 int main() {
16 ThreadPool pool;
17 for (int i =0; i< 10; i++){
18 ThreadTask task;
19 if (i % 2 == 0){
20 task.SetTask(i, test_func); //init
21 }else {
22 task.SetTask(i, tmp_func);
23 }
24 pool.TaskPush(task);
25 }
26 sleep(1000);
27 return 0;
28 }
运行结果: