进程池&线程池原理及应用

来源:互联网 发布:cpda数据分析师 含金量 编辑:程序博客网 时间:2024/05/18 12:43


一般我们是通过动态创建子进程(或子线程)来实现并发服务器的,但是会存在这样一些缺点:
1、动态创建进程(或线程)比较耗费时间,这将导致较慢的服务器响应。
2、动态创建的子进程通常只用来为一个客户服务,这样导致了系统上产生大量的细微进程(或线程)。进程和线程间的切换将消耗大量CPU时间。
3、动态创建的子进程是当前进程的完整映像,当前进程必须谨慎的管理其分配的文件描述符和堆内存等系统资源,否则子进程可能复制这些资源,从而使系统的可用资源急剧下降,进而影响服务器的性能。
所以呢,就引入了进程池与线程池的概念。
————————————————————————————————————————————————–
进程池与线程池原理相似,以线程池为例来说明
线程池的作用:有效的降低频繁创建销毁线程所带来的额外开销。
线程池的原理:线程池都是采用预创建的技术,在应用启动之初便预先创建一定数目的线程。应用在运行的过程中,需要时可以从这些线程所组成的线程池里申请分配一个空闲的线程,来执行一定的任务,任务完成后,并不是将线程销毁,而是将它返还给线程池,由线程池自行管理。如果线程池中预先分配的线程已经全部分配完毕,但此时又有新的任务请求,则线程池会动态的创建新的线程去适应这个请求。当然,有可能,某些时段应用并不需要执行很多的任务,导致了线程池中的线程大多处于空闲的状态,为了节省系统资源,线程池就需要动态的销毁其中的一部分空闲线程。因此,线程池都需要一个管理者,按照一定的要求去动态的维护其中线程的数目。
选择子线程为新客户服务的方式:
1、主线程使用某种算法来主动选择子线程。最简单、最常用的算法是随机算法和Round Robin(轮流算法);
2、主线程和所有子线程通过一个共享的工作队列来实现同步:子线程都睡眠在该工作队列上,当有新的任务到来时,主线程将任务添加到工作队列中。这将唤醒正在等待任务的子线程,不过只有一个子线程将获得新任务的“接管权”,它可以从工作队列中取出任务并执行之,而其他子线程将继续睡眠在工作队列上。
3、当选择好子线程后,主线程程还需要使用某种通知机制来告诉目标子线程有新任务需要处理,并传递必要的数据。我们可以把这些数据定义为全局,那么它们本身就是被所有线程共享的。对于进程池而言,最简单的方式是,在父进程和子进程之间预先建立好一条管道,然后通过管道来实现所有的进程间通信。
线程池主要用于:
1、需要大量的线程来完成任务,且完成任务的时间比较短。 Web服务器完成网页请求这样的任务,使用线程池技术是非常合适的。因为单个任务小,而任务数量巨大,一个热门网站的点击次数会很多。
但对于长时间的任务,比如一个Telnet连接请求,线程池的优点就不明显了。因为Telnet会话时间比线程的创建时间大多了。
2、对性能要求苛刻的应用,比如要求服务器迅速响应客户请求。
3、接受突发性的大量请求,但不至于使服务器因此产生大量线程的应用。
————————————————————————————————————————————————–
通过一个线程池的例子来进一步理解:

//线程池里所有运行和等待的任务都是一个CThread_worker *由于所有任务都在链表里,所以是一个链表结构  typedef struct worker  {      void *(*process) (void *arg);//回调函数,任务运行时会调用此函数,注意也可声明成其它形式    void *arg;//回调函数的参数     struct worker *next;  } CThread_worker;    //线程池结构typedef struct  {      pthread_mutex_t queue_lock;      pthread_cond_t queue_ready;      CThread_worker *queue_head;//链表结构,线程池中所有等待任务      int shutdown; //是否销毁线程池     pthread_t *threadid;        int max_thread_num; //线程池中允许的活动线程数目     int cur_queue_size;//当前等待队列的任务数目   } CThread_pool;  int pool_add_worker (void *(*process) (void *arg), void *arg);  void *thread_routine (void *arg);  //share resource  static CThread_pool *pool = NULL;  void  pool_init (int max_thread_num)  {      pool = (CThread_pool *) malloc (sizeof (CThread_pool));      pthread_mutex_init (&(pool->queue_lock), NULL);      pthread_cond_init (&(pool->queue_ready), NULL);      pool->queue_head = NULL;      pool->max_thread_num = max_thread_num;      pool->cur_queue_size = 0;      pool->shutdown = 0;      pool->threadid = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t));      int i = 0;      for (i = 0; i < max_thread_num; i++)      {           pthread_create (&(pool->threadid[i]), NULL, thread_routine,NULL);      }  }  //向线程池中加入任务 int  pool_add_worker (void *(*process) (void *arg), void *arg)  {      CThread_worker *newworker = (CThread_worker *) malloc (sizeof (CThread_worker));   //构造一个新任务      newworker->process = process;      newworker->arg = arg;      newworker->next = NULL;    pthread_mutex_lock (&(pool->queue_lock));      CThread_worker *member = pool->queue_head;//将任务加入到等待队列中    if (member != NULL)      {          while (member->next != NULL)          member = member->next;          member->next = newworker;      }      else      {          pool->queue_head = newworker;      }      assert (pool->queue_head != NULL);      pool->cur_queue_size++;      pthread_mutex_unlock (&(pool->queue_lock));      //等待队列中有任务了,唤醒一个等待线程;注意如果所有线程都在忙碌,这句没有任何作用      pthread_cond_signal (&(pool->queue_ready));      return 0;  }  //销毁线程池,等待队列中的任务不会再被执行,但是正在运行的线程会一直 把任务运行完后再退出int  pool_destroy ()  {      if (pool->shutdown)          return -1;//防止两次调用    pool->shutdown = 1;      //唤醒所有等待线程,线程池要销毁了    pthread_cond_broadcast (&(pool->queue_ready));      //阻塞等待线程退出,否则就成僵尸了    int i;      for (i = 0; i < pool->max_thread_num; i++)          pthread_join (pool->threadid[i], NULL);      free (pool->threadid);      //销毁等待队列     CThread_worker *head = NULL;      while (pool->queue_head != NULL)      {          head = pool->queue_head;          pool->queue_head = pool->queue_head->next;          free (head);      }      //条件变量和互斥量也别忘了销毁     pthread_mutex_destroy(&(pool->queue_lock));      pthread_cond_destroy(&(pool->queue_ready));         free (pool);      pool=NULL;  //销毁后指针置空      return 0;  }  void *  thread_routine (void *arg)  {      printf ("starting thread 0x%x\n", pthread_self ());      while (1)      {          pthread_mutex_lock (&(pool->queue_lock));          //如果等待队列为0并且不销毁线程池,则处于阻塞状态; 注意pthread_cond_wait是一个原子操作,等待前会解锁,唤醒后会加锁         while (pool->cur_queue_size == 0 && !pool->shutdown)          {              printf ("thread 0x%x is waiting\n", pthread_self ());              pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock));          }          //线程池要销毁了        if (pool->shutdown)          {              //遇到break,continue,return等跳转语句,千万不要忘记先解锁              pthread_mutex_unlock (&(pool->queue_lock));              printf ("thread 0x%x will exit\n", pthread_self ());              pthread_exit (NULL);          }          printf ("thread 0x%x is starting to work\n", pthread_self ());          assert (pool->cur_queue_size != 0);          assert (pool->queue_head != NULL);          //等待队列长度减去1,并取出链表中的头元素        pool->cur_queue_size--;          CThread_worker *worker = pool->queue_head;          pool->queue_head = worker->next;          pthread_mutex_unlock (&(pool->queue_lock));          //调用回调函数,执行任务         (*(worker->process)) (worker->arg);          free (worker);          worker = NULL;      }      //这一句应该是不可达的     pthread_exit (NULL);  }  //测试   void *  myprocess (void *arg)  {      printf ("threadid is 0x%x, working on task %d\n", pthread_self (),*(int *) arg);      sleep (1);//休息一秒,延长任务的执行时间     return NULL;  } int  main (int argc, char **argv)  {      pool_init (3);//线程池中最多三个活动线程        //连续向池中投入10个任务    int *workingnum = (int *) malloc (sizeof (int) * 10);      int i;      for (i = 0; i < 10; i++)      {          workingnum[i] = i;          pool_add_worker (myprocess, &workingnum[i]);      }      //等待所有任务完成      sleep (5);      //销毁线程池      pool_destroy ();       free (workingnum);      return 0;  }  

这里写图片描述