I used gcc-4.8.1(configure: ./configure --prefix=/usr/local) to compile following code in Ubuntu 12.04, but when I ran it, it didn't work. it didn't stop to wait the mutex. It returned false, and outputed "Hello world!"
command: g++ -std=c++11 main.cpp -omain -pthread
When I used gcc-4.6(apt-get install g++) to compile it, it worked well. The program waited about ten seconds, and outputed "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; }
If I am not mistaken, that is Bug 54562 -mutex and condition variable timers.
The reason for the bug is also mentioned:
This is because it uses the CLOCK_MONOTONIC clock (if available on the platform) to calculate the absolute time when it needs to return, which is incorrect as the POSIX pthread_mutex_timedlock() call uses the CLOCK_REALTIME clock, and on my platform the monotonic clock is way behind the real time clock.
However, this doesn't explain why you see the correct behavior on gcc-4.6
though. Perhaps _GLIBCXX_USE_CLOCK_MONOTONIC
is not enabled?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With