多进程内线程并、串行执行关系验证

 目的:

看下父进程内多个线程间是否并行、串行执行

查看父子进程中线程并行、串行执行

 

示例:

操作步骤:

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.o
	gcc main.o -o main -lpthread

main.o:main.c
	gcc -c -Wall main.c -o main.o 

.PHONY:clean
clean:
	rm -rf *.o main

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值