11

I am just wondering if there is any locking policy in C++11 which would prevent threads from starvation.

I have a bunch of threads which are competing for one mutex. Now, my problem is that the thread which is leaving a critical section starts immediately compete for the same mutex and most of the time wins. Therefore other threads waiting on the mutex are starving.

I do not want to let the thread, leaving a critical section, sleep for some minimal amount of time to give other threads a chance to lock the mutex.

I thought that there must be some parameter which would enable fair locking for threads waiting on the mutex but I wasn't able to find any appropriate solution.

Well I found std::this_thread::yield() function, which suppose to reschedule the order of threads execution, but it is only hint to scheduler thread and depends on scheduler thread implementation if it reschedule the threads or not.

Is there any way how to provide fair locking policy for the threads waiting on the same mutex in C++11? What are the usual strategies?

Thanks

4

1 回答 1

8

这是互斥锁中的常见优化,旨在避免在同一线程可以再次获取互斥锁时浪费时间切换任务。如果当前线程在其时间片中仍有剩余时间,那么您可以通过让它获取互斥锁而不是挂起它并切换到另一个线程(这可能会导致缓存线的大重新加载和各种其他延迟)。

如果您对互斥锁有太多争论,以至于这是一个问题,那么您的应用程序设计就是错误的。您将所有这些线程都阻塞在互斥体上,因此什么也不做:没有这么多线程您可能会更好。

您应该设计您的应用程序,以便如果多个线程竞争一个互斥锁,那么哪个线程获得锁并不重要。直接争用也应该是一种罕见的事情,尤其是与大量线程的直接争用。

我认为这是一个好的场景的唯一情况是每个线程都在等待一个条件变量,然后将其广播以唤醒它们。然后每个线程都会争夺互斥锁,但如果你这样做是正确的,那么他们都应该快速检查这不是虚假唤醒,然后释放互斥锁。即使这样,这也被称为“雷声”的情况,并不理想,正是因为它序列化了所有这些线程。

于 2013-07-03T08:32:25.633 回答