操作系统那些事儿之同步互斥与进程线程

一、信号量,可用资源个数,等待该资源的进程数
假如说与某资源关联的信号量初值为 3,当前值为 1。若 M 表示该资源的可用个数,N 表示等待该资源的进程数,则 M, N 分别是1, 0,

信号量初值 = 3,表示系统中该资源有 3 个单位。
当前信号量值 = 1,表示现在还有 1 个单位的资源是空闲的,即可用资源 M = 1。
若当前值为 1,说明有两个资源已被占用(3 - 1 = 2),而没有进程在等待,否则信号量值会是负数(等待进程数 = -信号量值)。
因为当前值是正数(1),所以说明等待队列是空的,即N = 0

二、著名的 Peterson 算法,它是一个经典的、基于软件的、解决两个进程间临界区问题的方案。该算法巧妙地通过两个共享变量 flag 和 turn 来保证进程互斥、防止死锁和饥饿。

// --- 共享变量及初始值 ---
// Shared variables and their initial values

boolean flag[2];  // flag[i] is true if process Pi wants to enter the critical section
int turn;         // Indicates whose turn it is to enter the critical section

// Initialization
flag[0] = false;
flag[1] = false;
turn = 0; // or 1, the initial value is not critical

// --- 进程 P₀ 的代码 ---
// Code for Process P₀

void P0() {
    while (true) {
        // --- 进入区 (Entry Section) ---
        flag[0] = true;              // P₀ signals its intent to enter
        turn = 1;                    // Politely give the turn to P₁
        while (flag[1] && turn == 1); // Wait if P₁ also wants to enter AND it's P₁'s turn

        // --- 临界区 (Critical Section) ---
        // ... (critical operations here) ...
        // --- 临界区结束 ---

        // --- 退出区 (Exit Section)---
        flag[0] = false;             // P₀ is done, retracts its intent
        
        // --- 剩余区 (Remainder Section) ---
    }
}

// --- 进程 P₁ 的代码 ---
// Code for Process P₁

void P1() {
    while (true) {
        // --- 进入区 (Entry Section) ---
        flag[1] = true;              // P₁ signals its intent to enter
        turn = 0;                    // Politely give the turn to P₀
        while (flag[0] && turn == 0); // Wait if P₀ also wants to enter AND it's P₀'s turn

        // --- 临界区 (Critical Section) ---
        // ... (critical operations here) ...
        // --- 临界区结束 ---

        // --- 退出区 (Exit Section)---
        flag[1] = false;             // P₁ is done, retracts its intent
        
        // --- 剩余区 (Remainder Section) ---
    }
}

三、

posted @ 2025-07-03 21:11  浅影镜心  阅读(25)  评论(0)    收藏  举报