http://hi.baidu.com/lingiloveyou/blog/item/b09ad82fc4b1aa281e3089d4.html
线程池的实现基本上是一个生产者消费者模型,具体就是1个生产者对应多个多个消费者。主线程对应其中的生产者,将到达的客户请求进行封装后送到商店供消费者使用(这里的商店可以用链表或是其它容器来实现),而线程池中的多个工作线程就是这些商品(客户请求)的消费者。
当编写测试程序时,常常需要让线程阻塞一段时间,类似于进程中的sleep函数。由于各个操作系统的实现不同,使得sleep函数在不同的OS上有不同的动作。有些OS中在线程中调用sleep,将会阻塞整个进程,而有些OS则只会阻塞调用线程。若想测试自己的OS中sleep的表现情况,可用如下代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
void* t1(void* a){
pid_t t = getpid();
printf("pid = %d\n",t);
printf("thread %d begins\n",pthread_self());
sleep(10);
printf("thread %d ends\n",pthread_self());
}
void* t2(void* a){
pid_t t = getpid();
printf("pid = %d\n",t);
int i = 0;
printf("thread %d begins\n",pthread_self());
for(; i < 10 ;++i){
printf("thread %d is running\n",pthread_self());
sleep(1);
}
}
int main(){
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1,NULL,t1,NULL);
pthread_create(&tid2,NULL,t2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
在不知道自己的OS究竟表现如何的情况下,可用select函数实现线程的定时阻塞。类似如:
select(0, NULL, NULL, NULL, &time)
其实,如果知道使用的线程库是 nptl ( native posix thread library),则可直接使用sleep来实现。但若使用的线程库是linuxthreads,则sleep就很不确定了。
判断系统中的线程库可用命令:
# getconf GNU_LIBPTHREAD_VERSION
NPTL 0.60 (输出)
另外在编译多线程程序时,需要指定线程库,使用linuxthreads线程库和使用nptl线程库的方法是在编译时添加相应的选项,两个线程库对应的选项如下:
linuxthreads : -lpthread
nptl : -nptl
NPTL使Linux内核可以非常有效的运行使用POSIX线程标准写的程序。测试数据表明,在32位机下,NPTL成功启动100000个线程只用了2秒,而不使用NPTL将需要大约15分钟左右的时间。