关闭

Linux下设计一个简单的线程池

发表于:2011-8-03 10:26

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:hinyunsin(CSDNblog)    来源:51Testing软件测试网采编

  线程池设计

  数据结构设计

  任务设计

typedef struct tp_work_desc_s TpWorkDesc; 
typedef void (*process_job)(TpWorkDesc*job); 
struct tp_work_desc_s { 
         void *ret; //call in, that is arguments  
         void *arg; //call out, that is return value  
};

  其中,TpWorkDesc是任务参数描述,arg是传递给任务的参数,ret则是任务处理完成后的返回值;

  process_job函数是任务处理函数原型,每个任务处理函数都应该这样定义,然后将它作为参数传给线程池处理,线程池将会选择一个空闲线程通过调用该函数来进行任务处理;

  线程设计

typedef struct tp_thread_info_s TpThreadInfo; 
struct tp_thread_info_s { 
         pthread_t thread_id; //thread id num  
         TPBOOL is_busy; //thread status:true-busy;flase-idle  
         pthread_cond_t thread_cond; 
         pthread_mutex_t thread_lock; 
         process_job proc_fun; 
         TpWorkDesc* th_job; 
         TpThreadPool* tp_pool; 
};

  TpThreadInfo是对一个线程的描述。

  thread_id是该线程的ID;

  is_busy用于标识该线程是否正处理忙碌状态;

  thread_cond用于任务处理时的唤醒和等待;

  thread_lock,用于任务加锁(此处保留);

  proc_fun是当前任务的回调函数地址;

  th_job是任务的参数信息;

  tp_pool是所在线程池的指针;

  线程池设计

typedef struct tp_thread_pool_s TpThreadPool; 
struct tp_thread_pool_s { 
         unsigned min_th_num; //min thread number in the pool  
         unsigned cur_th_num; //current thread number in the pool  
         unsigned max_th_num; //max thread number in the pool  
         pthread_mutex_t tp_lock; 
         pthread_t manage_thread_id; //manage thread id num  
         TpThreadInfo* thread_info; 
         Queue idle_q; 
         TPBOOL stop_flag; 
}; 

《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号