Presentation is loading. Please wait.

Presentation is loading. Please wait.

2017 Operating Systems 作業系統實習 助教:陳主恩、林欣穎 實驗室:720A Lab9 1.

Similar presentations


Presentation on theme: "2017 Operating Systems 作業系統實習 助教:陳主恩、林欣穎 實驗室:720A Lab9 1."— Presentation transcript:

1 2017 Operating Systems 作業系統實習 助教:陳主恩、林欣穎 實驗室:720A Lab9 1

2 samaphore範例 samaphore 介紹 實作 目錄 Contents Beaglebone Beaglebone
2

3 1-1 semaphore 介紹 信號(semaphore)
Semaphore是一個variable (變數)或是abstract data type (抽象資料型別),提供平行運算環境中,控制多個process (程序)或thread(執行緒)存取共享資源的能力,Semaphore可以用於紀錄某一特定資源剩下多少數目可使用;process或thread透過semaphore可以安全的使用共享資源,若特定資源已使用完時,會需要等待資源被釋放。雖然semaphore在防止deadlock或race condition方面是一個很有用的工具,但是程式使用semaphore運作上並無法保證一定不會遇到這些問題。 Ex: 類似圖書館的研究室使用,假設有10間研究室(SEM_VALUE_MAX=10),若學生要使用研究室便需要向櫃檯申請,櫃檯會記錄有多少間研究室使用中,若10間研究室都被申請使用後,且仍有學生要申請使用,該學生必須等待有其他學生離開,空出研究室後,才能進入使用,該櫃檯就扮演semaphore的角色。 3

4 1-2 semaphore 介紹 信號(semaphore) Semaphore包含兩種:
binary semaphore(二進位信號) binary semaphore值只能是0或1,在邏輯上相當於一個mutex(互斥鎖)。mutex使用上與binary semaphore具有相同功能,但是,mutex主要設計是防止兩個process同時間執行相同的一段code或存取同一資料,而binary semaphore設計上則是限制同時間存取同一資源;很多應用上mutex具有owner(擁有者)的概念,只有鎖住mutex的process,才具有解鎖的權限;相對的,semaphore並無此限制 counting semaphore(計數信號) counting semaphore值依據semaphore.h的SEM_VALUE_MAX (semvmx)定義。也有作業系統稱作general semaphore。 4

5 2-1 Semaphore範例 函式宣告: 標頭檔: #include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int val); 第一個參數為semaphore的位址,第二個參數為設定semaphore是否可讓不同process使用,第三個參數為semaphore初始值。 說明: 一個semaphore並非被單一thread所擁有,亦即一個thread對semaphore執行sem_wait()時,另一thread可以執行sem_post()。但是作業系統在實作時,同一時間點僅能執行其中一個指令,以維持semaphore的一致性。 int sem_wait(sem_t *sem); 減少semaphore值(減1) int sem_post(sem_t *sem); 增加semaphore值(加1) 傳回值: int sem_destory(sem_t *sem); 銷毀semaphore Semaphore動作執行成功會回傳0,失敗會回傳 -1 5

6 Semaphore 範例 2-2 Semaphore 程式碼 gcc test1.c –lpthread –o test1 6

7 2-2 Semaphore 範例 Semaphore 程式碼
   sem_t empty:信號量empty控制盤子可放水果數,初始為3,因為開始盤子為空可放水果數為3。 sem_t  apple ;信號量apple控制兒子可吃的蘋果數,初始為0,因為開始盤子裡沒蘋果。 3.sem_t orange;信號量orange控製女兒可吃的橙子是,初始為0,因為開始盤子裡沒橙子。 7

8 實作課本第六章的project1和project3,並抽問問題 (使用附件程式) 完成test2.c生產者與消費者的程式碼,並執行編譯
8

9 Thanks 作業系統實習 Operating Systems


Download ppt "2017 Operating Systems 作業系統實習 助教:陳主恩、林欣穎 實驗室:720A Lab9 1."

Similar presentations


Ads by Google