各位看官好,上回講父子進程,今天探討進程互斥——讓多進程按序訪問臨界資源。
互斥指兩個進程按一定順序使用臨界資源。如鍵盤:父進程用時子進程必須等待,父進程釋放後子進程才能用。
示例代碼中用count模擬臨界資源:
int main() {
pid_t pid = fork();
int count = 0;
if (pid > 0) { // 父進程
count++; printf("Father count=%d\n", count);
} else if (pid == 0) { // 子進程
count++; printf("Son count=%d\n", count);
}
}
運行結果:父子進程幾乎同時操作count,各自輸出count=1,無任何順序協調。
wait()實現互斥wait()讓父進程阻塞,直到子進程結束:
if (pid > 0) {
pid_t pid_res = wait(&stat_value); // 等待子進程結束
if (pid_res > 0) {
count++; // 子進程結束後父進程才操作count
printf("Father count=%d\n", count);
}
} else if (pid == 0) {
count++; // 子進程先操作
printf("Son count=%d\n", count);
}
PID: 3073 -> Father Process is running // 父進程未操作count
PID: 3074 -> Son Process is running
count is 1 in Son Process // 子進程先用
Son process finished: PID = 3074 // 子進程結束
count is 1 in Father Process // 父進程後用
明顯看到:子進程先完成對臨界資源的訪問,父進程隨後,實現了順序互斥。
wait()通常在父進程調用,回收子進程狀態,避免殭屍進程完整代碼在資源區。下回繼續進程停止話題,敬請期待!