【操作系统原理】【实验2】创建、观察进程和线程的并发执行

一、实验目的

观察进程的创建和切换

二、实验内容

1.0 题目

step1:编写一个c语言程序:
初始化一个count变量为1;
使用fork函数创建两个子进程,每个子进程对count加1之后,显示“I am son, count=?”或“I am daughter, count=?”,?使用count值代替。
父进程对count加1之后,显示“I am father, count=?”,?使用count值替代。最后,父进程使用waitpid等待两个子进程结束后退出
step2:编译后,运行该程序,观察
屏幕上显示结果的顺序性,直至出现不一样的情况为止
观察每行打印结果中count的值。

1.1 源代码

#include <unistd.h>
#include <stdio.h>
int main()
{
	pid_t son_pid, daughter_pid;
	int count = 1;
	son_pid = fork();
	if (son_pid == 0)
	{
		count++;
		printf("I am son, count=%d
", count);
	}
	else
	{
		daughter_pid = fork();
		if (daughter_pid == 0)
		{
			count++;
			printf("I am daughter, count=%d
", count);
		}
		else
		{
			count++;
			printf("I am father, count=%d
", count);
		}
	}
	return 0;
}

1.2 运行结果截图

二、线程的创建和切换

2.0 题目

step1:编写一个c语言程序:
初始化一个count变量为1;
使用pthread_create函数创建两个线程,每个线程对count加1之后,显示“I am son, count=?”或“I am daughter, count=?”,?使用count值代替。
父进程对count加之后,显示“I am father, count=?”,?使用count值替代。最后,父进程使用pthread_join等待两个线程结束后退出
step2:编译后,运行该程序,观察
屏幕上显示结果的顺序性,直至出现不一样的情况为止
观察每行打印结果中count的值。

2.1 源代码

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

void *daughter(void *num)
{
	int* a = (int*)num;
	*a += 1;
	printf("I am daughter, count=%d
", *a);
}

void *son(void *num)
{
	int* a = (int*)num;
	*a += 1;
	printf("I am son, count=%d
", *a);
}

int main(void)
{
	pthread_t son_tid, daughter_tid;
	int count = 1;
	pthread_create(&son_tid, NULL, son, &count);
	pthread_create(&daughter_tid, NULL, daughter, &count);
	count++;
	printf("I am parent, count=%d
", count);
	pthread_join(son_tid, NULL);
	pthread_join(daughter_tid, NULL);
	return 0;
}

2.2 运行结果截图

三、实验结果及分析

在进程实验中,创建出来的进程拥有独立的变量池,所以每次对count进行加减都是对每个进程独立的变量进行加减,
最后输出时,每个进程的变量都是独立加减的结果。
而在线程实验中,各个线程共享进程的变量,所以每个线程对变量进行加减,操作的都是同一个变量,
最后输出时,count值时累加的。

有了计划记得推动,不要原地踏步。
原文地址:https://www.cnblogs.com/amnotgcs/p/15496149.html