2016-12-16 55 views
-1

根信號執行一般信號量實現並採用二進制信號:使用二進制信號

click image please, gen semaphore implemented using binary semaphores

所以我無法理解爲什麼我們需要進入信號,我可以看到它是如何工作正常,沒有它。 多個進程如何進入臨界區?第一個進程進入後,它等待(互斥),這意味着沒有其他人可以進入,此外還有其他進程正在等待信號(互斥)

一般信號量可以允許多個進程進入關鍵部分區域,但我不明白在這段代碼中是如何完成的。

+0

爲什麼會投票,我不會說得太好,請編輯一下,如果需要的話 – JessicaRam

+0

首先不要張貼圖片的代碼。 – EOF

+0

'entry'信號量可以防止多個進程同時等待'delay'信號量。還可以防止'c'低於'-1'。 – user3386109

回答

0

看到你的問題圖像後,入口信號量的目的是隻允許單個進程/線程等待鎖定,如果你不使用它,其他進程將進入等待隊列。

爲什麼我們需要進入信號

  • 進入信號不與任何值初始化,如果它是全局聲明,然後它會與0所以,如果進入信號爲0,等待初始化(進入)將只允許單個進程進入,因爲wait()函數檢查入口值是否小於零,那麼進程將進入等待隊列。

多個進程如何進入臨界區?

  • 一次只能有一個進程處於關鍵部分 - 否則關鍵部分是什麼?

  • 關鍵部分是訪問共享變量 並且必須作爲原子動作執行的代碼段。這意味着在合作進程的組 中,在給定的時間點,只有一個進程 必須執行其臨界區。如果任何其他進程 想要執行其關鍵部分,則它必須等到第一個 結束。

一般的信號可以允許多個進程進入臨界區面積,但我不能看到如何在此代碼完成。

這是不正確的,如果您允許多個進程到想要修改共享數據的關鍵部分,那麼您可以更改關鍵部分的平均值。您將在流程結束時收到錯誤的數據。

如果進程只讀取共享數據,一般信號量可用於允許多個進程訪問關鍵數據,而不會修改共享數據。

我有很小的代碼讓你看看信號量如何工作以及多個進程如何允許訪問共享數據。你可以把它當作多個讀者和一個作家。

semaphore mutex = 1;     // Controls access to the reader count 
semaphore db = 1;     // Controls access to the database 
int reader_count;     // The number of reading processes accessing the data 

Reader() 
{ 
    while (TRUE) {      // loop forever 
    down(&mutex);       // gain access to reader_count 
    reader_count = reader_count + 1;  // increment the reader_count 
    if (reader_count == 1) 
     down(&db);       // if this is the first process to read the database, 
              // a down on db is executed to prevent access to the 
              // database by a writing process 
    up(&mutex);       // allow other processes to access reader_count 
    read_db();        // read the database 
    down(&mutex);       // gain access to reader_count 
    reader_count = reader_count - 1;  // decrement reader_count 
    if (reader_count == 0) 
     up(&db);       // if there are no more processes reading from the 
              // database, allow writing process to access the data 
    up(&mutex);       // allow other processes to access reader_countuse_data(); 
              // use the data read from the database (non-critical) 
} 

Writer() 
{ 
    while (TRUE) {      // loop forever 
    create_data();       // create data to enter into database (non-critical) 
    down(&db);        // gain access to the database 
    write_db();       // write information to the database 
    up(&db);        // release exclusive access to the database 
} 
相關問題