一直担心在线程里加sleep会引起进程所有的线程挂起,测试过了不会
- #include <pthread.h>
- #include <stdio.h>
- #include <sys/time.h>
- #include <string.h>
- #include <unistd.h>
- #define MAX 10
- pthread_t thread[2];
- void * thread1()
- {
- while(1)printf ("thread1 : I'm thread 1\n");
- }
- void * thread2()
- {
- printf("thread2 : I'm thread 2\n");
- sleep(3);
- printf("thread2 : I'm thread 2 end\n");
- exit(0);
- }
- void thread_create(void)
- {
- int temp;
- memset(&thread, 0, sizeof(thread));
- if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)
- printf("create thread 1 fail\n");
- else
- printf("create thread 1 success\n");
- if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)
- printf("create thread 2 fail\n");
- else
- printf("create thread 2 success\n");
- }
- void thread_wait(void)
- {
- if(thread[0] !=0) { //comment4
- pthread_join(thread[0],NULL);
- printf("thread1 end\n");
- }
- if(thread[1] !=0) { //comment5
- pthread_join(thread[1],NULL);
- printf("thread2 end\n");
- }
- }
- int main()
- {
- printf("i am main\n");
- thread_create();
- printf("mail waitin \n");
- thread_wait();
- return 0;
- }
sleep不会耗CPU时间的。sleep时内核直接把该线程丢进in active的队列,根本不会去调度它,直到sleep时间完了,时钟中断来了才会唤醒该线程进入active队列。
>>为什么pthread_create中的回调函数必须都要有类似于sleep的函数才可以让多个线程之间可以切换。
sleep确实可以让出CPU,但通常很少有用sleep来让出CPU的。原因有两个:1.sleep的单位是秒,而一个进程默认的时间片是20ms,以这个粒度让出CPU明显太大了,要用也该用usleep;2.通过睡眠让出CPU通常你不知道这个线程应该休眠多久,什么时候该被唤醒。更通用的方式是使用类似poll这样的系统调用,在没有事件到达前就一直睡眠,有事件到达再唤醒。