計算信號量的問題

有一些情況需要同時在臨界區執行多個進程。 但是,當我們需要同時在臨界區中有多個進程時,可以使用計數信號量。

信號量實現的編程代碼如下所示,其中包括信號量的結構以及在臨界區中可以執行的入口和退出的邏輯。

struct Semaphore
{
    int value; // processes that can enter in the critical section simultaneously.
    queue type L; // L contains set of processes which get blocked
}
Down (Semaphore S)
{
    SS.value = S.value - 1; //semaphore's value will get decreased when a new
    //process enter in the critical section
    if (S.value< 0)
    {
        put_process(PCB) in L; //if the value is negative then
        //the process will get into the blocked state.
        Sleep();
    }
    else
        return;
}
up (Semaphore s)
{
    SS.value = S.value+1; //semaphore value will get increased when
    //it makes an exit from the critical section.
    if(S.value<=0)
    {
        select a process from L; //if the value of semaphore is positive
        //then wake one of the processes in the blocked queue.
        wake-up();
    }
    }
}

在這種機制中,臨界區的入口和退出是根據計數信號量的值執行的。在任何時間點計算信號量的值表示可以同時在臨界區輸入的最大進程數。

想要進入臨界區的進程首先將信號量值減1,然後檢查它是否為負值。如果它變為負數,則該過程被推入阻塞過程的列表(即q),否則它進入臨界區。

當進程從臨界區退出時,它會將計數信號量增加1,然後檢查它是否為負值或零。如果它是負數,那麼這意味著至少有一個進程在阻塞狀態下等待,因此,為了確保有界等待,阻塞進程列表中的第一個進程將被喚醒並進入臨界區。

被阻止列表中的進程將按其睡眠順序進行喚醒。如果計數信號量的值為負數,則表示處於阻塞狀態的進程數量,如果為正數,則表示臨界區域中可用的插槽數量。


上一篇: 信號量介紹 下一篇: 計算信號量的問題