//threadpool.h

#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <pthread.h>
#include <deque>
#include <vector>
class ThreadPool{
  typedef void (*Task)();
public:
  ThreadPool(int num);

  //线程池启动
  void start();

  //加入任务
  void addTask(Task task);

  //每个线程创建时实际运行函数
  static void* Routine(void *arg);

  //线程创建后实际运行函数,由Routine调用,用于获取任务并执行
  void runInThread();
  ~ThreadPool();
private:
  int num_;
  std::deque<Task> queue_;
  //线程控制三件套
  std::vector<pthread_t> thread_;
  pthread_mutex_t mtx_;
  pthread_cond_t notEmpty_;
};
#endif
//threadpool.cc

#include "threadpool.h"

ThreadPool::ThreadPool(int num):
  num_(num),
  queue_(std::deque<Task>()),
  thread_(std::vector<pthread_t>(num))
{
    pthread_cond_init(&notEmpty_, NULL);
    pthread_mutex_init(&mtx_, NULL);
}

void* ThreadPool::Routine(void *arg)
{
  ThreadPool* tp = static_cast<ThreadPool*>(arg);
  tp -> runInThread();
  return NULL;
}

void ThreadPool::start()
{  
  //创建线程
  for(int i = 0;i < num_; ++i)
    pthread_create(&thread_[i], NULL, Routine, (void*)this);
}

void ThreadPool::runInThread()
{

  while(1){
    pthread_mutex_lock(&mtx_);
    //等待有任务
    while(queue_.empty())
      pthread_cond_wait(&notEmpty_, &mtx_);
    //获取任务
    Task task = queue_.front();
    queue_.pop_front();
    pthread_mutex_unlock(&mtx_);
    //运行任务
    task();
  
  }
}

void ThreadPool::addTask(Task task)
{
  pthread_mutex_lock(&mtx_);
  queue_.push_back(task); 
  pthread_mutex_unlock(&mtx_);
  pthread_cond_signal(&notEmpty_);
}

测试:

//main.cc

#include "threadpool.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>

static int cnt = 0;

void test(){
  printf("now tid is %d \n", syscall(SYS_gettid));
  unsigned long i = 0xfffffff;
  while(i--);
  printf("%d\n", ++cnt);
  sleep(1);
} 

int main(int argc, char **argv){
// printf("0");
  ThreadPool* tp = new ThreadPool(2);
  //printf("1");
  tp -> start();
  //printf("2");
  sleep(1);
  int i = 10;
  while(i--){
    tp -> addTask(test);
  }
  sleep(20);
}

测试结果: