Linux:实现一个简单的线程池

线程池

一、定义:线程池是一种线程使用模式。

二、目的:线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。可用线程数量应该取决于可用的并发处理器、处理器内核、内存、网络sockets等的数量。

三、应用场景:

  • 需要大量的线程来完成任务,且完成任务的时间比较短。 WEB服务器完成网页请求这样的任务,使用线程池技术是非常合适的。因为单个任务小,而任务数量巨大,你可以想象一个热门网站的点击次数。 但对于长时间的任务,比如一个Telnet连接请求,线程池的优点就不明显了。因为Telnet会话时间比线程的创建时间大 多了。
  • 对性能要求苛刻的应用,比如要求服务器迅速响应客户请求。  
  • 接受突发性的大量请求,但不至于使服务器因此产生大量线程的应用。突发性大量客户请求,在没有线程池情况下,将产生大量线程,虽然理论上大部分操作系统线程数目最大值不是问题,短时间内产生大量线程可能使内存到达极限,出现错误. 

四、线程池示例:

        功能:1. 创建固定数量线程池,循环从任务队列中获取任务对象, 

                    2. 获取到任务对象后,执行任务对象中的任务接口

  • 代码实现:
/* 线程池 */  

#ifndef __M_POOL_H_
#define __M_POOL_H_ 

#include<stdio.h>
#include<iostream>
#include<queue>
#include<error.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>

#define MAX_THREAD 5
#define MAX_QUEUE 10

typedef bool (*HandleFunc)(int data);

class MyTask
{
  private:
    int _data;
    HandleFunc _handleFunc;
  public:
    MyTask(){}
    MyTask(int data,HandleFunc handleFunc)
      :_data(data)
       ,_handleFunc(handleFunc) {}

    ~MyTask(){}
   void SetTask(int data,HandleFunc handleFunc)
   {
     _data = data;
     _handleFunc = handleFunc;
   }
   bool Run()
   {
     return _handleFunc(_data);
   }
};

class MyThreadPool
{
  private:
    int max_thread;   //线程池中最大线程数
    int cur_thread;   //当前线程池中的线程数
    int quitFlag;     //线程池中线程退出的标志
    int max_queue;    //队列的最大节点数
    std::queue<MyTask> task_list;    //任务队列

    pthread_mutex_t mutex;    //互斥量
    pthread_cond_t empty;     //条件变量
    pthread_cond_t full;      //条件变量

    void ThreadLock()       //加锁
    {
      pthread_mutex_lock(&mutex);
    } 
    void ThreadUnLock()     //解锁
    {
      pthread_mutex_unlock(&mutex);
    }

    void ConsumerWait()    //消费者等待(为空则等待)
    {
      if(quitFlag == true)  //所有任务均完成,则线程退出
      {
        cur_thread--;
        pthread_mutex_unlock(&mutex);
        printf("Thread[%p] exited.\n",pthread_self());
        pthread_exit(NULL);
      }
      pthread_cond_wait(&empty,&mutex);
    }
    void ConsumerWake()  //唤醒消费者
    {
      pthread_cond_signal(&empty);
    }
    void ConsumerWakeAll()  //广播唤醒剩余所有线程
    {
      pthread_cond_broadcast(&empty);
    }
    void ProducterWait()   //生产者等待(满了则等待)
    {
      pthread_cond_wait(&full,&mutex);
    }
    void ProducterWake() //唤醒生产者
    {
      pthread_cond_signal(&full);
    }
    bool QueueEmpty()
    {
      return task_list.empty();
    }
    bool QueueFull()
    {
      return (task_list.size() == max_queue ? true : false);
    }
    void QueuePush(MyTask& task)      //将task放入任务队列
    {
      task_list.push(task);
    }
    void QueuePop(MyTask* task)       //从任务队列取出task
    {
      *task = task_list.front();
      task_list.pop();
    }

  public:
    MyThreadPool(int maxt = MAX_THREAD,int maxq = MAX_QUEUE)
      :max_thread(maxt)
       ,max_queue(maxq)
    {
      cur_thread = maxt;
      quitFlag = false;
      pthread_mutex_init(&mutex,NULL);
      pthread_cond_init(&empty,NULL);
      pthread_cond_init(&full,NULL);
    } 
    ~MyThreadPool()
    {
      pthread_mutex_destroy(&mutex);
      pthread_cond_destroy(&empty);
      pthread_cond_destroy(&full);
    }

    static void* ThreadFunc(void* arg)  //线程执行函数
    {
      std::cout<<"In ThreadFunc()"<<std::endl;
      MyThreadPool* p = (MyThreadPool*)arg;
      while(1)
      {
        p->ThreadLock();
        while(p->QueueEmpty())        //任务队列没任务
          p->ConsumerWait();
        MyTask task;
        p->QueuePop(&task);
        p->ProducterWake();
        p->ThreadUnLock();
        task.Run();
      }
      return NULL;
    }
    bool MyThreadPool_Init()       //初始化线程池
    {
      pthread_t tid;
      int ret;
      for(int i = 0;i<max_thread;++i)      //创建线程
      {
        ret = pthread_create(&tid,NULL,ThreadFunc,(void*)this);
        if(ret != 0)     //pthread_create()返回值不为0说明创建失败
        {
          perror("pthread_create");
          return false;
        }
        pthread_detach(tid);     //线程分离
      }
      return true;
    }

    bool AddTask(MyTask& task)      //向任务队列添加任务
    {
      ThreadLock();
      if(quitFlag == true)    //线程不玩了
      {
        ThreadUnLock();
        return false;
      }
      while(QueueFull())      //任务队列已满
        ProducterWait();
      QueuePush(task);
      ConsumerWake();
      ThreadUnLock();
      return true;
    }
    void MyThreadPool_Quit()      //线程池退出
    {
      std::cout<<"In MyThreadPool_Quit"<<std::endl;
      ThreadLock();
      quitFlag = true;
      ThreadUnLock();
      while(cur_thread > 0)   //退出线程池内的所有线程
      {
        ConsumerWakeAll();    
        usleep(3000);
      }
    }
};

bool TaskHandle(int data)
{
  srand((unsigned int)time(NULL));
  int n = rand()%5;
  printf("Thread[%p] is ready to sleep for %d seconds.\n",pthread_self(),n);
  sleep(n);
  return true;
}

int main()
{
  MyThreadPool p;
  p.MyThreadPool_Init();

  MyTask task[10];
  for(int i =0;i<10;++i)
  {
    task[i].SetTask(i,TaskHandle);
    p.AddTask(task[i]);
    printf("task[%d] : Add success!\n ",i);
  }

  p.MyThreadPool_Quit();
  return 0;
}

#endif 
  • 运行之:

  • 运行步骤:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章