ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

C线程池

2021-06-30 23:32:14  阅读:243  来源: 互联网

标签:线程 void cond pthread threads pool


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

在这里插入图片描述

​ 作者:hackett ​ ​ 微信公众号:加班猿 ​

 

C线程池

1、准备工作

查看线程相关接口函数:

线程创建

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

设置线程的cancle信号

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);

存在多个等待线程时按入队顺序激活其中一个

2、创建数据结构

任务结构体

 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;

3、线程池函数

初始化线程池

 /*
  * @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);
  }
 ​
  pthread_exit(NULL);
 }

 

线程池里取消线程

 /*
  * @description: 线程池里取消线程
  * @param {thread_pool*} pool:线程池结构体指针 {nsigned int} removing_threads: 取消的线程数
  * @return: 失败返回-1
  */
 int remove_thread(thread_pool *pool, unsigned int removing_threads)
 {
  if(removing_threads == 0)
  return pool->active_threads;
 ​
  int remain_threads = pool->active_threads - removing_threads;
  remain_threads = remain_threads>0 ? remain_threads:1;
 ​
  int i;
  for(i=pool->active_threads-1; i>remain_threads-1; i--)
  {
  errno = pthread_cancel(pool->tids[i]);
  if(errno != 0)
  break;
  }
 ​
  if(i == pool->active_threads-1)
  return -1;
  else
  {
  pool->active_threads = i+1;
  return i+1;
  }
 }

销毁线程池

 /*
  * @description: 销毁线程池
  * @param {thread_pool*} pool:线程池结构体指针
  * @return: 成功返回true
  */
 bool destroy_pool(thread_pool *pool)
 {
 ​
  pool->shutdown = true;
  pthread_cond_broadcast(&pool->cond);
 ​
  int i;
  for(i=0; i<pool->active_threads; i++)
  {
  errno = pthread_join(pool->tids[i], NULL);
  if(errno != 0)
  {
  printf("join tids[%d] error: %s\n",
  i, strerror(errno));
  }
  else
  printf("[%u] is joined\n", (unsigned)pool->tids[i]);
 
  }
 ​
  free(pool->task_list);
  free(pool->tids);
  free(pool);
 ​
  return true;
 }

4、完整代码

由于篇幅较长就不贴出来 代码放百度云,需要的在微信公众号回复【线程】即可获取链接下载

使用:Linux下进入文件夹执行make生成可执行文件test执行即可

image-20210630224505511

如果你觉得文章还不错,可以给个"三连"

我是加班猿,我们下期见

 

标签:线程,void,cond,pthread,threads,pool
来源: https://www.cnblogs.com/hackettt/p/14956913.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有