简体   繁体   中英

Valid use cases for `std::timed_mutex`?

In which situations would a std::timed_mutex be preferred over a regular mutex?

The only use-case I can think of would be as a (IMO hackish) way to prevent deadlocks.

In what other situations would a std::timed_mutex be a good choice?

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.

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.

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. 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). So do sysv semaphores on OS X and BSD. It's a useful tool to have, if you are smart enough to only use it when appropriate.

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

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