日期:2014-05-16  浏览次数:20704 次

关于linux线程执行顺序的问题
这是个简单的多线程实现,
我想请问:当主线程sleep后,理应执行子线程,1s之后再返回主线程的,
但是有没有这样的可能,主线程sleep之后,没有去执行子线程,反而去执行系统其他的进程,最后1s到后,直接返回了主线程,最后导致子线程没有被执行?会不会出现这种情况?
1. #include<stdio.h>   
2. #include<pthread.h>   
3. #include<stdlib.h>   
4. #include<unistd.h>   
5. #include<signal.h>   

6. static void thread_one(char* msg);   

8. int  main(int argc, char** argv)   
9. {   
10.     pthread_t th_one;   
11.     char * msg="thread";   
12.     printf("thread_one starting/n");   
13.     if(pthread_create(&th_one,NULL,(void*)&thread_one,msg)!=0)   
14.     {   
15.         exit(EXIT_FAILURE);   
16.     }   
17.    
18.     
23.     printf("Main thread will sleep 1 S/n");   
24.     sleep(1);//@2   
25.     return 0;   
26.        
27. }   
28. static void thread_one(char* msg)   
29. {   
30.     int i=0;   
31.     while(i<6)   
32.     {   
33.         printf("I am one. loop %d/n",i);   
34.         i++;   

36.     }   
37. }   

linux,线程,进程,执行顺序

------解决方案--------------------
有可能,在没有更多前提限定下,取决于具体调度算法,系统资源就绪情况(比如code page需要从远程文件系统load进来),当前系统load,线程间优先级,线程affinity,等等

------解决方案--------------------
引用:
请问cody2k3大哥。
如果先后建立两个子线程,那先建立的子线程也不一定先获得资源喽?

完全有可能啊,因为进程之间的调度本来就是抢占式的。