Why is std :: timed_mutex :: try_lock_for not working?

I used gcc-4.8.1 (configure: ./ configure --prefix = / usr / local) to compile the following code on Ubuntu 12.04, but when I ran it, it did not work. he did not stop to wait for the mutex. It returns false and prints "Hello world!"

: g ++ -std = C ++ 11 main.cpp -omain -pthread

When I used gcc-4.6 (apt-get install g ++) to compile it, it worked fine. The program waited about ten seconds and displayed "Hello world!"

#include <thread> #include <iostream> #include <chrono> #include <mutex> std::timed_mutex test_mutex; void f() { test_mutex.try_lock_for(std::chrono::seconds(10)); std::cout << "hello world\n"; } int main() { std::lock_guard<std::timed_mutex> l(test_mutex); std::thread t(f); t.join(); return 0; } 
+6
source share
2 answers

If I am not mistaken, this is Error 54562 -mutex and variable condition timers .

The cause of the error is also mentioned:

This is due to the fact that it uses the CLOCK_MONOTONIC clock (if available on the platform) to calculate the absolute time when it should be returned, which is incorrect, since the POSIX call pthread_mutex_timedlock () is used, the clock is CLOCK_REALTIME, and on my platform it is a monotonous clock per clock real time.

However, this does not explain why you see the correct behavior on gcc-4.6 . Perhaps _GLIBCXX_USE_CLOCK_MONOTONIC not enabled?

+6
source

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.

0
source

Source: https://habr.com/ru/post/948910/


All Articles