[问题] 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