一个Linux下C线程池的实现
什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。下面是Linux系统下用C语言创建的一个线程池。线程池会维护一个任务链表(每个CThread_worker结构就是一个任务)。pool_init()函数预先创建好max_thread_num个线程,每个线程执thread_routine ()函数。该函数中
while (pool->cur_queue_size == 0)
{
pthread_cond_wait (&(pool->queue_ready),&(pool->queue_lock));
}
表示如果任务链表中没有任务,则该线程出于阻塞等待状态。否则从队列中取出任务并执行。pool_add_worker()函数向线程池的任务链表中加入一个任务,加入后通过调用pthread_cond_signal (&(pool->queue_ready))唤醒一个出于阻塞状态的线程(如果有的话)。pool_destroy ()函数用于销毁线程池,线程池任务链表中的任务不会再被执行,但是正在运行的线程会一直把任务运行完后再退出。下面贴出完整代码
#include
#include
#include
#include
#include
#include
/*
*线程池里所有运行和等待的任务都是一个CThread_worker
*由于所有任务都在链表里,所以是一个链表结构
*/
typedef struct worker
{
/*回调函数,任务运行时会调用此函数,注意也可声明成其它形式*/
void *(*process) (void *arg);
void *arg;/*回调函数的参数*/
struct worker *next;
} CThread_worker;
/*线程池结构*/
typedef struct
{
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
/*链表结构,线程池中所有等待任务*/
CThread_worker *queue_head;
/*是否销毁线程池*/
int shutdown;
pthread_t *threadid;
/*线程池中允许的活动线程数目*/
int max_thread_num;
/*当前等待队列的任务数目*/
int cur_queue_size;
} CThread_pool;
int pool_add_worker (void *(*process) (void *arg), void *arg);
void *thread_routine (void *arg);
static CThread_pool *pool = NULL;
void
pool_init (int max_thread_num)
{
pool = (CThread_pool *) malloc (sizeof (CThread_pool));
pthread_mutex_init (&(pool->queue_lock), NULL);
pthread_cond_init (&(pool->queue_ready), NULL);
pool->queue_head = NULL;
pool->max_thread_num = max_thread_num;
pool->cur_queue_siz
相关文档:
C输出格式总结
2007-07-08 12:09
1 一般格式
printf(格式控制,输出表列)
例如:printf("i=%d,ch=%c\n",i,ch);
说明:
(1)“格式控制”是用双撇号括起来的字符串,也称“转换控制字符串”,它包括两种信息:
&nbs ......
【1】 “ = ”的优先级低于 “ || ” 且 “ = ” 为右结合性,注意一下代码为死循环:while(c=' '||c=='\t'||c=='\n')
程序本意是跳过空格,制表符,换行符,但由于不小心将c==' '写成了c= ' '导致程序进入死循环
【2】a=-1 在很老的C版本里理解为 a =- 1
【3 ......
http://www.gamedev.net/reference/programming/features/orgfiles/page2.asp
通过四个pitfall讲解头文件的由来和好处,以及使用头文件定义inline func and template.
Remember that, as far as the compiler is concerned, there is absolutely no difference between a header file and a source file.
The key idea ......
ARM C嵌入式编程中的几个关键字
1、访问绝对地址的内存位置:
#define pISR_EINT0 (*(unsigned *) (_ISR_STRATADDRESS+0x74))
上述语句把无符号整数_ISR_STRATADDRESS+0x74强制转换为指针,指向RAM,用下面的语句可以访问它:
pISR_EINT0 = (int)Eint0_ISR
& ......