date:
updated:
C线程池

作者: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、创建数据结构
任务结构体
1 2 3 4 5 6
| struct task { void *(*task)(void *arg); void *arg; struct task *next; };
|
线程池结构体
1 2 3 4 5 6 7 8 9 10
| typedef struct thread_pool { pthread_mutex_t lock; pthread_cond_t cond; struct task *task_list; pthread_t *tids; unsigned waiting_tasks; unsigned active_threads; bool shutdown; }thread_pool;
|
3、线程池函数
初始化线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
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; }
|
向线程池添加任务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
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; }
|
向线程池添加线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
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; }
|
线程的回调处理函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
void handler(void *arg) {
pthread_mutex_unlock((pthread_mutex_t *)arg); }
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); }
|
线程池里取消线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
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; } }
|
销毁线程池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
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执行即可

如果你觉得文章还不错,可以给个”三连“
我是加班猿,我们下期见
