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

看板C_and_CPP (C/C++)作者時間7年前 (2018/05/22 20:25), 編輯推噓2(206)
留言8則, 3人參與, 7年前最新討論串1/1
開發平台(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
pthread_create的第二個參數pthread_attr_t
05/22 21:37, 2F

05/22 21:38, 7年前 , 3F
有很多可以調 無聊可以試試看 基本上都不會特別管他
05/22 21:38, 3F

05/22 21:39, 7年前 , 4F
之前有遇過專案把讀檔的priority調高 但現在的電腦
05/22 21:39, 4F

05/22 21:39, 7年前 , 5F
沒特別感覺出差別
05/22 21:39, 5F

05/23 09:47, 7年前 , 6F
即使是thread的切換還是會有context switch,我想應該是當
05/23 09:47, 6F

05/23 09:47, 7年前 , 7F
你沒特別實作進出critical section規則時,kernel會按它即有
05/23 09:47, 7F

05/23 09:47, 7年前 , 8F
排程來做
05/23 09:47, 8F
文章代碼(AID): #1R10mfR5 (C_and_CPP)
文章代碼(AID): #1R10mfR5 (C_and_CPP)