简体   繁体   English

`std :: timed_mutex`的有效用例?

[英]Valid use cases for `std::timed_mutex`?

In which situations would a std::timed_mutex be preferred over a regular mutex? 在哪种情况下, std :: timed_mutex比普通的互斥锁更受欢迎?

The only use-case I can think of would be as a (IMO hackish) way to prevent deadlocks. 我能想到的唯一用例是作为(IMO hackish)防止死锁的方法。

In what other situations would a std::timed_mutex be a good choice? 在其他情况下std::timed_mutex会是一个不错的选择吗?

That's a common design practice on Windows, where you'd use either WaitForSingleObject or WaitForMultipleObjects with a timeout value, specifying a time after which the wait should fail. 这是Windows上常见的设计实践,您可以使用具有超时值的WaitForSingleObjectWaitForMultipleObjects ,指定等待失败的时间。

It's not used to work around deadlocks (that really wouldn't help, badly-threaded code is badly-threaded code). 它不习惯解决死锁(实际上没有用,严重的线程代码是严格的线程代码)。

Keeping in mind that Windows did not have the equivalent of Posix condition variables until the release of Windows Vista, an entirely different multi-threaded coding paradigm developed, which plays a part but is not the sole reason for the existence of timed mutexes. 请记住,在Windows Vista发布之前,Windows没有等效的Posix条件变量,这是一种完全不同的多线程编码范例,它发挥了作用,但并不是定时互斥锁存在的唯一原因。

Usage of timed waits isn't something you'd see in a basic example, but in a complex architecture you'll run across it more often than not. 定时等待的使用不是您在基本示例中看到的,但在复杂的架构中,您经常会遇到它。 An example of where you would use a mutex is generally with some sort of producer-consumer architecture where the client must do something every x seconds, with the possibility of an "interrupt" in the form of an event being triggered. 使用互斥锁的示例通常是某种生产者 - 消费者体系结构,其中客户端必须每隔x秒执行一次操作,并且可能以触发事件的形式出现“中断”。 A simple pseudocode example: 一个简单的伪代码示例:

//This code will run indefinitely, printing the value of 
//the variable x every 1 second until an interrupt is received
while(timed_wait(end_mutex, 1 second) != success)
    print(x)

Yes, this code could be rewritten as follows: 是的,这段代码可以改写如下:

while(true){
   sleep(1 second)
   wait(mutex)
   done = globalDone
   unlock(mutex)

   if(done) break
   else print(x)
}

But the prior example is both cleaner and more responsive as it's not a sleep (ie any time the mutex becomes available, it'll stop). 但是前面的例子既清洁又响应更快,因为它不是睡眠(即任何时候互斥体变得可用,它就会停止)。

Note that Linux has additional functions not part of the Posix standard to do timed waits on mutexes ( pthread_mutex_timedlock , but I think it's now in the posix spec). 请注意,Linux有其他功能,不是Posix标准的一部分,用于对互斥锁进行定时等待( pthread_mutex_timedlock ,但我认为它现在在posix规范中)。 So do sysv semaphores on OS X and BSD. OS X和BSD上的sysv信号量也是如此。 It's a useful tool to have, if you are smart enough to only use it when appropriate. 如果你足够聪明只在适当时使用它,它是一个有用的工具。

定时互斥等待的最佳用例是仅在特定时间内有效的操作,因此在资源拥塞时它们应该失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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