title: C线程池 categories: - [C++] tags: - [编程语言] date: 2021/06/28

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void (start_routine) (void *), void *arg);
参数说明:
1.参数thread指向存放新创建线程的线程ID的地址
2.attr参数用于定制各种不同的线程属性,暂可以把它设置为NULL,以创建默认属性的线程。
3.start_routine是个函数指针,该函数返回类型是void,同时形式参数也是void。新创建的线程从start_routine函数的地址开始运行。该函数只有一个无类型指针参数arg.如果需要向start_routine函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。
返回值:
线程创建成功返回0,失败返回其他数值
void pthread_exit(void *retval);
参数说明:
retval是一个无类型指针,进程中的其他线程可以通过调用pthread_join函数访问到这个指针。
int pthread_join(pthread_t thread, void **retval);
参数说明:
调用这个函数的线程将一直阻塞,直到指定的线程调用pthread_exit. 如果对线程的返回值不感兴趣,可以把retval置为NULL。在这种情况下,调用pthread_join函数将等待指定的线程终止,但并不获得线程的终止状态。
int pthread_cancel(pthread_t thread);
参数说明:
thread为线程的id
int pthread_setcancelstate(int state, int *oldstate) ;
PTHREAD_CANCEL_ENABLE:线程可取消。这是所有新线程的默认取消状态,包括初始线程。线程的可取消类型决定了可取消线程何时响应取消请求。
PTHREAD_CANCEL_DISABLE:线程不可取消。如果收到一个取消请求,它将被阻塞,直到可取消启用。
void pthread_cleanup_push(void (*rtn)(void *), void *arg);
参数说明:
void(*rtn)(void *):线程清理函数
arg传递的参数
pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
参数说明:
1.在使用互斥锁前,需要定义互斥锁(全局变量),定义互斥锁对象形式为:pthread_mutex_t lock;
2.mutex 是个指针,指向需要初始化的互斥锁;
3.参数attr指定了新建互斥锁的属性。如果参数attr为NULL,则使用默认的互斥锁属性,默认属性为快速互斥锁 。
int pthread_mutex_destroy(pthread_mutex_t *mutex);
参数说明:
mutex为需要销毁的互斥锁;
int pthread_mutex_lock(pthread_mutex_t *mutex);
参数说明:
mutex为需要加锁的互斥锁;
int pthread_mutex_unlock(pthread_mutex_t *mute);
参数说明:
mutex为需要解锁的互斥锁;
条件变量是利用
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
参数说明:
1.cond为初始化的条件变量,是一个指向结构pthread_cond_t的指针;
2.cond_attr为cond_attr是一个指向结构pthread_condattr_t的指针;
int pthread_cond_destroy(pthread_cond_t *cond);
参数说明:
cond为销毁的条件变量;
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
int pthread_cond_signal(pthread_cond_t *__cond);
存在多个等待线程时按入队顺序激活其中一个
 struct task
 {
     void *(*task)(void *arg);   /* 任务需要执行的函数 */
     void *arg;                  /* 执行函数的参数 */
     struct task *next;          /* 下一个任务的地址 */
 };
 typedef struct thread_pool
 {
     pthread_mutex_t lock;
     pthread_cond_t  cond;
     struct task *task_list; /*链表结构,线程池中所有等待任务*/
     pthread_t *tids;        /*存放线程id的指针*/
     unsigned waiting_tasks; /*当前等待的任务数*/
     unsigned active_threads;/*线程池中线程数目*/
     bool shutdown;          /*是否销毁线程池*/
 }thread_pool;
 /*
  * @description: 初始化线程池
  * @param {thread_pool*} pool:线程池结构体指针 {unsigned int} max_thread_num: 创建几个线程
  * @return: false 失败 true 成功
  */
 bool init_pool(thread_pool *pool, unsigned int threads_number)
 {
     pthread_mutex_init(&pool->lock, NULL);  /*初始化线程锁*/
     pthread_cond_init(&pool->cond, NULL);   /*初始化条件变量*/
 ?
     pool->shutdown = false;                 
     pool->task_list = malloc(sizeof(struct task));
     pool->tids = malloc(sizeof(pthread_t) * MAX_ACTIVE_THREADS);
 ?
     if(pool->task_list == NULL || pool->tids == NULL)
     {
         perror("allocate memory error");
         return false;
     }
 ?
     pool->task_list->next = NULL;
 ?
     pool->waiting_tasks = 0;
     pool->active_threads = threads_number;
 ?
     int i;
     for(i=0; i<pool->active_threads; i++)
     {
         if(pthread_create(&((pool->tids)[i]), NULL,
                     routine, (void *)pool) != 0)
         {
             perror("create threads error");
             return false;
         }
     }
     return true;
 }
 /*
  * @description: 向线程池添加任务
  * @param {thread_pool*} pool:线程池结构体指针 {void *(void *arg)} (*task): 线程的回调函数 {void *} arg: 传入的参数
  * @return: false 失败 true 成功
  */
 bool add_task(thread_pool *pool,
             void *(*task)(void *arg), void *arg)
 {
     struct task *new_task = malloc(sizeof(struct task));
     if(new_task == NULL)
     {
         perror("allocate memory error");
         return false;
     }
     new_task->task = task;
     new_task->arg = arg;
     new_task->next = NULL;
 ?
 ?
     pthread_mutex_lock(&pool->lock);
     if(pool->waiting_tasks >= MAX_WAITING_TASKS)
     {
         pthread_mutex_unlock(&pool->lock);
 ?
         fprintf(stderr, "too many tasks.\n");
         free(new_task);
 ?
         return false;
     }
     
     struct task *tmp = pool->task_list;
     while(tmp->next != NULL)
         tmp = tmp->next;
 ?
     tmp->next = new_task;
     pool->waiting_tasks++;
 ?
 ?
     pthread_mutex_unlock(&pool->lock);
     pthread_cond_signal(&pool->cond);
 ?
     return true;
 }
 /*
  * @description: 向线程池添加线程
  * @param {thread_pool*} pool:线程池结构体指针 {unsigned int} additional_threads: 添加的线程数
  * @return: 返回成功的线程数
  */
 int add_thread(thread_pool *pool, unsigned int additional_threads)
 {
     if(additional_threads == 0)
         return 0;
 ?
     unsigned int total_threads =
              pool->active_threads + additional_threads;
 ?
     int i, actual_increment = 0;
     for(i = pool->active_threads;
         i < total_threads && i < MAX_ACTIVE_THREADS;
         i++)
     {
         if(pthread_create(&((pool->tids)[i]),
                 NULL, routine, (void *)pool) != 0)
         {
             perror("add threads error");
 ?
             if(actual_increment == 0)
                 return -1;
 ?
             break;
         }
         actual_increment++; 
     }
 ?
     pool->active_threads += actual_increment;
     return actual_increment;
 }
 /*
  * @description: 回调处理函数
  * @param  {void *} arg: 传入的参数
  * @return: 无
  */
 void handler(void *arg)
 {
 ?
     pthread_mutex_unlock((pthread_mutex_t *)arg);
 }
 /*
  * @description: 线程的回调处理函数
  * @param  {void *} arg: 传入的参数
  * @return: 无
  */
 void *routine(void *arg)
 {
     thread_pool *pool = (thread_pool *)arg;
     struct task *p;
 ?
     while(1)
     {
 ?
         pthread_cleanup_push(handler, (void *)&pool->lock);
         pthread_mutex_lock(&pool->lock);
 ?
 ?
         while(pool->waiting_tasks == 0 && !pool->shutdown)
         {
             pthread_cond_wait(&pool->cond, &pool->lock);
         }
 ?
 ?
         if(pool->waiting_tasks == 0 && pool->shutdown == true)
         {
             pthread_mutex_unlock(&pool->lock);
             pthread_exit(NULL);
         }
 ?
 ?
         p = pool->task_list->next;
         pool->task_list->next = p->next;
         pool->waiting_tasks--;
 ?
 ?
         pthread_mutex_unlock(&pool->lock);
         pthread_cleanup_pop(0);
 ?
 ?
         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
         (p->task)(p->arg);
         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
 ?
         free(p);
     }