linux 线程池编程,Linux-C-9-线程池编程

线程池

线程池:因为线程在频繁的进行创建和销毁过程中浪费CPU资源,线程池就是把一堆线程放在一个池子里面进行统一管理;

线程池工作流程:

1、初始化线程池,任务队列和工作线程;

2、向任务队列中添加任务;

3、将等候在条件变量(任务队列上有任务)上的一个线程唤醒并从该任务队列中取出第一个任务给该线程执行;

4、等待任务队列中所有任务执行完毕

5、关闭线程池;

线程池的构成

任务队列job_queue:用于存放待处理的函数,包含的成员有void *(*)(void *):用于表示处理函数,void *arg:用于表示参数选项,struct job_queue* pnext:队列指针;

worker:表示工作线程,用于处理任务;

thread_pool:表示线程池,作用是管理多个线程并且提供任务队列的接口;使用的函数包括:thread_pool_init():用于初始化线程池thread_pool_destory():用于销毁线程,thread_pool_dd_job():用于添加线程池任务;

一个线程池的例子

thread_pool_test.c

#include

#include

#include "thread_pool.h"

void* test(void* arg){

printf("%lu do job %d\n",pthread_self(),(int)arg);

}

int main(int argc,char* argv[]){

if(3 != argc){

printf("usage:%s \n",argv[0]);

return 1;

}

int nthread = atoi(argv[1]);

if(nthread <= 0){

printf("nthread must >0");

return 1;

}

struct threadpool* ppool = threadpool_init(nthread);

int njobs = atoi(argv[2]);

int i;

for(i=1;i

threadpool_add_job(ppool,test,(void*)i);

}

//pause();

threadpool_destroy(ppool);

}

线程池编程需要包含的头文件

thread_pool.h

#pragma once

#ifndef _THREAD_POOL_H_

#define _THREAD_POOL_H_

#include

#include

#include

#include

struct threadpool;

struct threadpool* threadpool_init(int nthreads);

void threadpool_add_job(struct threadpool* ppool,void* (*func)(void*),void* arg);

void threadpool_destroy(struct threadpool* ppool);

#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值