gpt4 book ai didi

c++ - 为什么 std::timed_mutex::try_lock_for 不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:40 34 4
gpt4 key购买 nike

我在 Ubuntu 12.04 中使用 gcc-4.8.1(configure: ./configure --prefix=/usr/local) 编译了以下代码,但是当我运行它时,它没有工作。它没有停下来等待互斥量。它返回 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();
return 0;
}

最佳答案

如果我没记错的话,那就是 Bug 54562 -mutex and condition variable timers

bug的原因也提到了:

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.

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

关于c++ - 为什么 std::timed_mutex::try_lock_for 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17518464/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com