【操作系統原理】【實驗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\n", count);
	}
	else
	{
		daughter_pid = fork();
		if (daughter_pid == 0)
		{
			count++;
			printf("I am daughter, count=%d\n", count);
		}
		else
		{
			count++;
			printf("I am father, count=%d\n", 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\n", *a);
}

void *son(void *num)
{
	int* a = (int*)num;
	*a += 1;
	printf("I am son, count=%d\n", *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\n", count);
	pthread_join(son_tid, NULL);
	pthread_join(daughter_tid, NULL);
	return 0;
}

2.2 運行結果截圖

三、實驗結果及分析

在進程實驗中,創建出來的進程擁有獨立的變量池,所以每次對count進行加減都是對每個進程獨立的變量進行加減,
最后輸出時,每個進程的變量都是獨立加減的結果。
而在線程實驗中,各個線程共享進程的變量,所以每個線程對變量進行加減,操作的都是同一個變量,
最后輸出時,count值時累加的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM