Possible workaround:
const int WAIT_PRECISION_MS = 10; // Change it to whatever you like int TIME_TO_WAIT_MS = 2000; // Change it to whatever you like int ms_waited = 0; bool got_lock = false; while (ms_waited < TIME_TO_WAIT_MS) { std::this_thread::sleep_for( std::chrono::milliseconds(WAIT_PRECISION_MS)); ms_waited += WAIT_PRECISION_MS; got_lock = YOUR_MUTEX.try_lock(); if (got_lock) { break; } }
WAIT_PRECISION_MS will tell the while loop how often to "wake up" and try to get a lock. But it will also tell how accurate your deadline will be if your exact time is not a factor in the final time.
For instance:
deadline = 20, precision = 3 : 3 is not a factor of 20 - the last iteration of the while loop will be when ms_waited is 18. This means that you will wait a total of 21 ms, not 20 ms.
deadline = 20, accuracy = 4 : 4 - coefficient 20 - the last iteration of the while loop will be ms_waited 16. This means that you are going to wait exactly 20 ms, since your deadline is determined.
source share