目的:
看下父进程内多个线程间是否并行、串行执行
查看父子进程中线程并行、串行执行
示例:
操作步骤:
1- fork创建两个进程:partent、child。
2- 在partent进程中利用pthread接口创建两个线程:thread_partent、thread_partent_hello
3- 在chile进程中创建一个线程:thread_child
4- 通过打印看下进程间执行是否有顺序。
观察结果:
1- 由于父进程中创建了两个线程,且在thread_partent_hello中加了耗时操作(for循环)耗时结束前有begain、end标志打印。观察thread_partent打印begain、end中间有thread_partent打印,表明thread_partent_hello运行时thread_partent也在运行。表明父进程中多个子进程并行执行
2- 子进程中也加入耗时计算,耗时前后有begain、end打印。在thread_child线程打印begain、end期间父进程的线程正常打印,表明,父子进程的线程间并行执行。
不确定这种实验方式设计的是否合理,结果的正确性也存疑。当然只是临时想法,做了个实验。
#include <stdio.h>
#include <sched.h>
#include <stdlib.h>
#include <unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>void * thread_partent()
{printf("%s(%d): thread ID:%lu\n",__func__,__LINE__,pthread_self());while(1){printf("partent thread\n");sleep(2);}pthread_exit(NULL);
}void * thread_partent_hello()
{int i=0;printf("%s(%d): thread ID:%lu\n",__func__,__LINE__,pthread_self());while(1){printf("partent hello world thread begain\n");for(i=0; i<1000000000; i++); printf("partent hello world thread end\n");sleep(2);}pthread_exit(NULL);
}void * thread_child()
{int i=0;printf("%s(%d): thread ID:%lu\n",__func__,__LINE__,pthread_self());while(1){printf("child thread bggain\n");for(i=0; i<100000000; i++); printf("child thread end\n"); sleep(1);}pthread_exit(NULL);
}int main(void)
{int result,ret;pthread_t partent,partent_hello;pthread_t child;result = fork();if(result>0){printf("parent parent=%d current=%d child=%d\n", getppid(), getpid(), result);ret = pthread_create(&partent, NULL,thread_partent, NULL);if(ret != 0){printf("thread creat fail!\n");}ret = pthread_create(&partent_hello, NULL,thread_partent_hello, NULL);if(ret != 0){printf("thread creat fail!\n");}}else{printf("child parent=%d current=%d\n", getppid(), getpid());ret = pthread_create(&child, NULL,thread_child, NULL);if(ret != 0){printf("thread creat fail!\n");}}printf("%s(%d): thread_strat begain exit!\n",__func__,__LINE__);pthread_join(partent,NULL);pthread_join(child,NULL);printf("%s(%d): thread_strat exit succ!\n",__func__,__LINE__); return 0;
}
#Makeile
main:main.ogcc main.o -o main -lpthreadmain.o:main.cgcc -c -Wall main.c -o main.o .PHONY:clean
clean:rm -rf *.o main