简体   繁体   中英

Use multiple std::unique_lock on mutex, all threads in FIFO to wait process?

When I have three threads or more, if mutex unlock in one thread, which one will be the next to process? They are in FIFO rule? If not FIFO, several thread wait unlock(), will have a thread never process? Do they wait in a sorted queue and what is the rule to sort them?

Sample code:

//thread No.1
func1(){
  std::unique_lock<mutex> lock(_mtx);
  //do something, now in here,and will leave this thread then mutex will unlock
}

//thread No.2
func2(){
  std::unique_lock<mutex> lock(_mtx);
  //do something
}

//thread No.3
func3(){
  std::unique_lock<mutex> lock(_mtx);
  //do something
}

The operating system will decide on which thread getting the mutex is the most efficient. It is your responsibility to ensure that whatever thread gets scheduled does work that you need it to do.

Generally, it's not possible for a thread to be denied the mutex for very long because eventually all the other threads will either block or exhaust their timeslices, allowing that thread to acquire the mutex. But the platform doesn't provide any particular guarantee of fairness.

You wouldn't want FIFO. That would be a complete disaster. Imagine if each thread needed to acquire the lock 100 times. Now one thread gets the lock, releases it, and then tries to get the lock against almost immediately. Do you want it to stop and switch to one of the other threads every time? Do you want 300 context switches and start/stops? You definitely don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM