代码之家  ›  专栏  ›  技术社区  ›  Jacinto Resende

STD::Simo::持续时间::()()不支持线程支持库

  •  1
  • Jacinto Resende  · 技术社区  · 6 年前

    我想做一个包装 std::timed_mutex 使用无限、notimeout和值超时的概念,而不是使用不同的库调用( lock , try_lock 等)。

    我假设如果我使用最大分辨率, std::chrono::nanoseconds ,其 max() 期限为292年。这足以代表无限的概念。

    但是我发现如果我用stl chrono 库助手类型,即 std::timed_mutex.try_lock_for(std::chrono::nanoseconds::max()) 出口(出口) false )当锁被其他线程拥有时。下面是一个快速演示应用程序。

    #include <cstdlib>
    #include <ratio>
    #include <chrono>
    #include <mutex>
    #include <thread>
    #include <iostream>
    
    #define STR_ME(expr_)   #expr_
    
    template <typename Duration>
    void check_infinity(const char *name,const Duration &timeout)
    {
        std::timed_mutex tmd_mx;
    
        tmd_mx.lock();  //mutex is locked by std::this_thread
        auto thread_f=[&](const char *name,Duration timeout)
                    {   
                        if (!tmd_mx.try_lock_for(timeout))  
                            std::cout << name << " : TIMEOUT!!" << std::endl;
                        else
                            std::cout << "Green light..." << std::endl;
                    };
    
        std::thread t{thread_f,name,timeout};
        std::this_thread::sleep_for(std::chrono::seconds(2));   //Ensures thread "t" runs.    
        t.join();
        std::cout << "Houston??" << std::endl;  //Shouldn't reach this point ever.
    }
    
    int main(int argc, char** argv) 
    {
        check_infinity(STR_ME(std::chrono::nanoseconds::max()),std::chrono::nanoseconds::max());    //Fails
        //Every other STL chrono::durations fail.    
    
        using my_nanoseconds    = std::chrono::duration<unsigned int,std::nano>;   //STL uses long.
        using my_seconds        = std::chrono::duration<unsigned int>;  
        check_infinity(STR_ME(my_nanoseconds::max()),my_nanoseconds::max());  // Fails
        check_infinity(STR_ME(my_seconds::max()),my_seconds::max());  // Works !!
    
        return EXIT_FAILURE;
    }
    

    在这个测试中,我在ubuntu中使用了pthread库。

    我的问题是:

    • 这是pthread库的“限制”吗?毕竟 最大() 持续时间对应于 rep 最大值。

    • 这个最大值是在什么地方定义的吗?

    • 这个最大值与CPU时钟有关吗?并且可以根据体系结构而变化?

    • 我在做傻事吗?
    1 回复  |  直到 6 年前
        1
  •  2
  •   Piotr Skotnicki    6 年前

    std::timed_mutex::try_lock_for 计算新的 std::chrono::time_point ,此时将根据当前时间点触发超时,并添加请求的超时持续时间。

    对于表示当前时间的任何非零时点(自纪元或自上次重新启动以来的时间),其分辨率不小于非秒(例如微秒),在添加 nanoseconds::max() (根据时钟的分辨率调整),即:

    steady_clock::now() + duration_cast<steady_clock::duration>(nanoseconds::max())
    

    溢出就像:

    int{1} + std::numeric_limits<int>::max()
    

    溢出,因为 std::chrono::nanoseconds::max() 收益率 [time.traits.duration_values]/p6 :

    static constexpr Rep max() noexcept;
    

    退换商品 : numeric_­limits<Rep>::max() .

    你的时钟的分辨率可能设定为 nanoseconds .