多线程sleep

linux c的sleep 和多线程测试

一直担心在线程里加sleep会引起进程所有的线程挂起,测试过了不会
 
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <sys/time.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #define MAX 10

  7. pthread_t thread[2];
  8. void * thread1()
  9. {
  10.     while(1)printf ("thread1 : I'm thread 1\n");
  11. }
  12. void * thread2()
  13. {
  14.     printf("thread2 : I'm thread 2\n");
  15.     sleep(3);
  16.     printf("thread2 : I'm thread 2 end\n");
  17.     exit(0);
  18. }
  19. void thread_create(void)
  20. {
  21. int temp;
  22. memset(&thread, 0, sizeof(thread));
  23. if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)
  24. printf("create thread 1 fail\n");
  25. else
  26. printf("create thread 1 success\n");
  27. if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)
  28. printf("create thread 2 fail\n");
  29. else
  30. printf("create thread 2 success\n");
  31. }
  32. void thread_wait(void)
  33. {
  34.     if(thread[0] !=0) { //comment4
  35. pthread_join(thread[0],NULL);
  36. printf("thread1 end\n");
  37. }
  38. if(thread[1] !=0) { //comment5
  39. pthread_join(thread[1],NULL);
  40. printf("thread2 end\n");
  41. }
  42. }
  43. int main()
  44. {
  45. printf("i am main\n");
  46. thread_create();
  47. printf("mail waitin \n");
  48. thread_wait();
  49. return 0;
  50. }

sleep不会耗CPU时间的。sleep时内核直接把该线程丢进in active的队列,根本不会去调度它,直到sleep时间完了,时钟中断来了才会唤醒该线程进入active队列。

>>为什么pthread_create中的回调函数必须都要有类似于sleep的函数才可以让多个线程之间可以切换。
sleep确实可以让出CPU,但通常很少有用sleep来让出CPU的。原因有两个:1.sleep的单位是秒,而一个进程默认的时间片是20ms,以这个粒度让出CPU明显太大了,要用也该用usleep;2.通过睡眠让出CPU通常你不知道这个线程应该休眠多久,什么时候该被唤醒。更通用的方式是使用类似poll这样的系统调用,在没有事件到达前就一直睡眠,有事件到达再唤醒。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值