开发者

multi thread in c question

开发者 https://www.devze.com 2023-01-03 17:41 出处:网络
Does mutex guarantee to execute thread in order of arriving? that is, if, thread 2 and thread 3 arrive is waiting while thread 1 is in critical section

Does mutex guarantee to execute thread in order of arriving?

that is, if, thread 2 and thread 3 arrive is waiting while thread 1 is in critical section

what exactly happen after thread 1 exit critical section if thread 2 arrive at mutex lock before thread 3, thread 2 will be allowed to enter crit开发者_开发问答ical section before thread 3 ?

or race condition will be occurred?

if its not guaranteed, how can i solve this? (maybe queue?)


That sort of behaviour would have to be an implementation detail of your threading library (which you didn't mention). I would guess most threading libraries don't make any such a guarantee, though. Unless the waiting threads had different priorities, of course.


Generally threading libraries do not make any such guarantees, because most OS's don't make any such guarantee. The thread wrapper can't (usually) do any better than the native OS thread management operations.


It's up to the operating system. In Windows, there is no guaranteed order that any given thread will be awoken and granted the mutex.


The question you have asked is classical case of "bounded waiting", and there is known way of solving this via [Bakery Algorithm].1

The basic idea here is that you maintain two counts, first is current serving number and other is global count (analogy to a bakery with a running number). Whenever a new thread enters (i.e. waits on a mutex) then increase the global count and give out ticket to the thread. This thread then waits on the ticket number, till the current serving number is equal to ticket number.

This way we can maintain the order such that thread which comes first, gets hold of mutex first.

I am not sure if the standard libraries implement mutex this way internally, but it wouldn't be that difficult to implement Bakery algorithm for your need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号