Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

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

3 mutex 介紹 1-1 互斥量(mutex) Thread Synchronization是使用Thread中難度比較高的地方,可能會遇到下列幾種情況: 有三個 Thread,一個Thread要等待另兩個 Thread 完成才能執行,但Thread一跑起來就是同時執行。 有兩個Thread互相依靠,Thread A是負責PUSH資料進入一個堆疊(Stack)中,Thread B是負責從Stack中POP資料出來,兩者不能同時使用Stack。 Thread要等待某一條件成立之後才能繼續執行。 3

4 thread 介紹 1-2 互斥量(mutex) POSIX Thread (pthread) Library 提供三種方法來做多執行緒的同步: Mutex: 使很多 Thread 同時只能有一個可以執行,其餘的必須等待。也就是使用mutex 鎖定,然後其他的Thread 就不能鎖定了,因此其他的Thread 則進入暫停(Blocking)的狀態,等待現在的thread將mutex解鎖釋放,這樣之後其他的Thread 就可以繼續的競爭mutex。 Join: 使 Thread 等待其他Thread 結束之後才可以繼續執行。 Condition variable: 透過一個變數來設定 Thread 是否可以跑,用來達到條件執行的功能。利用pthread_cond_ 函數群來完成。 4

5 2-1 A 定義mutex B C A 初始化mutex 使用mutex 銷毀mutex thread 範例 mutex
5

6 2-1 thread 範例 mutex API 函式宣告: pthread_mutex_t mutex
= PTHREAD_MUTEX_INITIALIZER; 標頭檔: #include <pthread.h> int pthread_mutex_init( pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr ); 說明: 鎖定和解除鎖定 mutex 變數,採用互斥的方式,同時間內只有一個Thread 可以鎖定mutex,其他的Thread 會Block住。 int pthread_mutex_destroy( pthread_mutex_t *mutex ); int pthread_mutex_lock ( pthread_mutex_t *mutex ); 傳回值: 傳回 0 代表成功,非 0 代表失敗 int pthread_mutex_unlock ( pthread_mutex_t *mutex ); 6

7 2-2 thread 範例 thread 程式碼 gcc mutex1.c –lpthread –o mutex1
如果使用了第4行的初始化方法,可以刪除22和27行。 7

8 將附件程式碼空白處填上正確的程式碼,並執行結果。
實作 將附件程式碼空白處填上正確的程式碼,並執行結果。 8

9 Thanks 作業系統實習 Operating Systems


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

Similar presentations


Ads by Google