一个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
相关文档:
一、屏幕操作函数
1. clrscr()清除字符窗口函数
2. window()字符窗口函数
3. gotoxy()光标定位函数
4. clreol() 清除光标行尾字符函数
5. insline() 插入空行函数
6. delline() 删除一行函数
7. gettext() 拷进文字函数
8. puttext() 拷出文字函数
9. movetext() 移动文字函数
二、字符属性函数
10. textmode( ......
【1】 “ = ”的优先级低于 “ || ” 且 “ = ” 为右结合性,注意一下代码为死循环:while(c=' '||c=='\t'||c=='\n')
程序本意是跳过空格,制表符,换行符,但由于不小心将c==' '写成了c= ' '导致程序进入死循环
【2】a=-1 在很老的C版本里理解为 a =- 1
【3 ......
1.引言
本文的写作目的并不在于提供C/C++程序员求职面试指导,而旨在从技术上分析面试题的内涵。文中的大多数面试题来自各大论坛,部分试题解答也参考了网友的意见。
许多面试题看似简单,却需要深厚的基本功才能给出完美的解答。企业要求面试者写一个最简单的strcpy函数都可看出面试者在技术上究竟达 ......
GCC 中文手册
http://www.nbfan.com/forum/dispbbs....&ID=1433&page=1
GNU make 指南
http:/ ......
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 ......