[問題] multi-thread mutex 的幾個問題

作者: shiningboy   2018-05-22 20:25:11
開發平台(Platform): (Ex: Win10, Linux, ...)
Linux
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)

問題(Question):
大家好,新手自學,
有一個問題想詢問
關於 multi-thread priority 的問題,
假設有下列程式碼
pthread_mutex_t mutex;
pthread_mutex_init(&mutex);
pthread_create(&thread_1 , NULL , same_func , NULL);
pthread_create(&thread_2 , NULL , same_func , NULL);
pthread_create(&therad_3 , NULL , same_func , NULL);
void * same_func(void *){
pthread_mutex_lock(&mutex);
//critical section code
pthread_mutex_unlock(&mutex);
}
一開始依序 create 3個 thread ,
假設 thread 1 最先進入了 same_func , 執行了 mutex lock
這時候在無法存取 critical section 的 thread_2 跟 thread_3 被 block
這時候 OS 會怎麼決定接下來當 thread_1 unlock 之後 ,
誰會可以先進入執行 mutex ???
是跟 process 一樣有 scheduler 用 priority 的高低來決定的嗎??
我自己實驗 loop 10000 次
常常會看到其中一個 thread 會重複好長一段時間重複佔據 mutex
例如 : 11111112222122331333333333333332222222222222211111111111111
大部分都是這樣的情況,很少會很平均的交替 12312312312312312312 這樣
這是有甚麼 scheduling rule 嗎?
如果要克服這個問題,
讓每個 thread 可以很平均的執行可以怎麼做呢?
要做 FIFO 嗎??
請大家幫忙解答了
謝謝
作者: bluesoul (忙死你老爸)   2018-05-22 20:30:00
你不要管他的順序,順其自然就好
作者: ilikekotomi (Young)   2018-05-22 21:37:00
pthread_create的第二個參數pthread_attr_t有很多可以調 無聊可以試試看 基本上都不會特別管他之前有遇過專案把讀檔的priority調高 但現在的電腦沒特別感覺出差別
作者: cphe (魔鬼藏在垃圾筒裡)   2018-05-23 09:47:00
即使是thread的切換還是會有context switch,我想應該是當你沒特別實作進出critical section規則時,kernel會按它即有排程來做

Links booklink

Contact Us: admin [ a t ] ucptt.com