【作業系統原理】【實驗2】程序執行緒的建立和切換
阿新 • • 發佈:2021-11-02
一、程序的建立和切換
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.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; }