关于线程的sleep函数

 

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分钟左右的时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值