[問題] multi-thread mutex 的幾個問題
開發平台(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 嗎??
請大家幫忙解答了
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.137.48.241
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1526991913.A.6C5.html
→
05/22 20:30,
7年前
, 1F
05/22 20:30, 1F
推
05/22 21:37,
7年前
, 2F
05/22 21:37, 2F
→
05/22 21:38,
7年前
, 3F
05/22 21:38, 3F
→
05/22 21:39,
7年前
, 4F
05/22 21:39, 4F
→
05/22 21:39,
7年前
, 5F
05/22 21:39, 5F
推
05/23 09:47,
7年前
, 6F
05/23 09:47, 6F
→
05/23 09:47,
7年前
, 7F
05/23 09:47, 7F
→
05/23 09:47,
7年前
, 8F
05/23 09:47, 8F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章