1:多线程设计通常是比较麻烦的,因为它牵涉到,线程间的同步、和执行顺序问题。在用户没有设定线程间的调度策略时,系统默认采取基于时间片轮转的调度策略。本实验是在默认的调度策略下,测试线程间的执行顺序问题。
本实验用的系统为Ubuntu10.04, Thread
gcc
2
- #include<stdio.h>
- #include<pthread.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<signal.h>
- static
void thread_one(char* msg); - static
void thread_two(char* msg); - int
main(int argc, char** argv) - {
-
pthread_t th_one,th_two; -
char * msg="thread"; -
printf("thread_one starting/n"); -
if(pthread_create(&th_one,NULL,(void*)&thread_one,msg)!=0) -
{ -
exit(EXIT_FAILURE); -
} -
sleep(1);// @1 -
printf("thread_two starting/n"); -
if(pthread_create(&th_two,NULL,(void*)&thread_two,msg)!=0) -
{ -
exit(EXIT_FAILURE); -
} -
printf("Main thread will sleep 1 S/n"); -
sleep(1);//@2 -
return 0; -
- }
- static
void thread_one(char* msg) - {
-
int i=0; -
while(i<6) -
{ -
printf("I am one. loop %d/n",i); -
i++; -
//sleep(1); -
} - }
- static
void thread_two(char* msg) - {
-
int i=0; -
while(i<6) -
{ -
printf("I am two. loop %d/n",i); -
i++; -
//sleep(1); -
} - }
2.1
2.1.1
在主线程没有执行等待的情况下,即@1和 @2 在注释掉的情况下。程序的运行如下。
thread_one
thread_two
Main
由此可见,多线程中子线程的执行是在主线程有空闲的条件下。即,如果主线程忙,或者是没有执行等待那么,子线程是不会执行的。
2.1.2
执行结果如下:
thread_one
I
I
I
I
I
I
thread_two
Main
程序在运行到I
可见,主线程在@1处,停了 1 秒,等待线程 1 执行,在线程 1 执行完毕后,有时还有时间,主线程继续等待完 1 秒后,重新执行。
2.1.3
执行结果如下:
thread_one
thread_two
Main
I
I
I
I
I
I
I
I
I
I
I
I
可见,在两个子线程运行后,主线程等待了1秒,这是有充分的时间让子线程完成执行。两个现成的执行顺序为先后顺序。
2.1.4
执行结果如下:
thread_one
I
I
I
I
I
I
thread_two
Main
I
I
I
I
I
I
程序在运行到I
在主线中,等待充分的时间使子线程执行,可以保证顺序执行。
2.1.5
程序执行结果如下:
thread_one
I
thread_two
Main
I
I
在@1 处,主线程等待了 1S ,让子线程 1 执行。子线程 1 执行一次循环,等待了 1S 。由于超过了主线程的等待时间,主线程在等待够 1S 后,继续执行。由于子线程 1 在子线程 2 显示输出时,被激活,所以子线程又循环一次后,子线程 2 输出结果。
2.1.6
程序执行如下:
thread_one
I
thread_two
Main
I
I
I
I
I
I