一个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
相关文档:
//输入参数:*str 搜索字符串
// subStrLen 用于返回找到的最大子字符串长度
//返回:找到的最大子字符串指针
char * findMaxSubStr(char *str, int &subStrLen){
char *subStr;
char *p = str;
int index[256] ;
for (int ix = 0; ix < sizeof(index)/sizeof(index[0]); ix++)
{
in ......
当要建立线程等时,在Linux下,用文本编辑,在键入“g++ -lpthread”.......“可以把库pthread引入”,编译通过。现在想用eclipse,但是默认情况下,引入不了pthread。会报“undefined reference to phread_create”等错误。
解决方法:可以在project中好到properties
在里面的&ldquo ......
索引:
1 输入与输出
1.1 文件操作
1.1.1 fopen
1.1.2 freopen
1.1.3 fflush
1.1.4 fclose
1.1.5 remove
1.1.6 rename
1.1.7 tmpfile
1.1.8 tmpnam
1.1.9 setvbuf
1.1.10 setbuf
1.2 格式化输出
1.2.1 fprintf
1.2.2 printf
1.2.3 sprintf
1.2.4 snprintf
1.2.5 vprintf
1.2.6 vfprintf
1.2.7 vsprintf ......
GCC 中文手册
http://www.nbfan.com/forum/dispbbs....&ID=1433&page=1
GNU make 指南
http:/ ......
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.为什 ......