一个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
相关文档:
原文:
http://www.codeproject.com/cpp/complex_declarations.asp
作者:Vikram A Punathambekar
介绍
曾经碰到过让你迷惑不解、类似于int * (* (*fp1) (int) ) [10];这样的变量声明吗?本文将由易到难,一步一步教会你如何理解这种复杂的C/C++声明:我们将从每天都能碰到的较简单的声明入手,然后逐步加入const修 ......
1、两个float型数据相加,也都先转化成double型,然后再相加,以提高运算精度。
2、求字节运算符sizeof,记住它不是一个函数。
3、++,--运算符只能用于变量,而不能用于常量或者表达式。
4、++,--的结合方向是“自右向左”。
int i=3;
cout<<-i++<<endl;
cout< ......
ARM C嵌入式编程中的几个关键字
1、访问绝对地址的内存位置:
#define pISR_EINT0 (*(unsigned *) (_ISR_STRATADDRESS+0x74))
上述语句把无符号整数_ISR_STRATADDRESS+0x74强制转换为指针,指向RAM,用下面的语句可以访问它:
pISR_EINT0 = (int)Eint0_ISR
& ......
1.gcc包含的c/c++编译器
gcc,cc与c++,g++
gcc和cc是一样的,c++和g++是一样的。一般c程序就用gcc编译,c++程序就用g++编译。
2.gcc的基本用法
gcc test.c:如果没有指定输出的文件,默认将编译出一个名为a.out的程序
gcc test.c -o test:-o参数用来指定生成目标程序的名字,这样将编译出一个名为test的程序。
3.为什 ......