为什么std :: timed_mutex :: try_lock_for不起作用? [英] Why does std::timed_mutex::try_lock_for not work?

查看:298
本文介绍了为什么std :: timed_mutex :: try_lock_for不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用gcc-4.8.1(configure:./configure --prefix = / usr / local)在Ubuntu 12.04中编译以下代码,但是当我运行它时,它没有用。并没有停止等待互斥体。它返回false,并输出 Hello world!。



命令:g ++ -std = c ++ 11 main.cpp -omain -pthread



当我使用gcc-4.6(apt-get install g ++)进行编译时,它运行良好。该程序等待了大约十秒钟,并输出了 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();
返回0;
}



解决方案

如果我没记错的话,那就是 Bug 54562 -mutex和条件变量计时器。 / p>

还提到了该错误的原因:


这是因为它使用了CLOCK_MONOTONIC时钟(如果在
平台上可用)来计算它需要返回的绝对时间,
是不正确的,因为POSIX pthread_mutex_timedlock()调用使用
的CLOCK_REALTIME时钟,然后在在我的平台上,单调时钟比实时时钟落后


但是,这并不能解释为什么您看到了在 gcc-4.6 上的正确行为。也许未启用 _GLIBCXX_USE_CLOCK_MONOTONIC


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?

这篇关于为什么std :: timed_mutex :: try_lock_for不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆