C ++ Chrono - 如何在std :: atomic <long long =“”>上使用duration_cast?

时间:2017-11-20 12:55:13

标签: multithreading c++11 chrono long-long

我有一个class Bar

class Bar
{
public:
    //...
private:
    std::atomic<long long>          m_keepAlive;
}

class有一些方法如下所述。

method获取ms中的纪元:

long long Bar::getTimeSinceEpoch()
{
    std::chrono::time_point<std::chrono::system_clock> p = std::chrono::system_clock::now();
    const long long epoch = std::chrono::duration_cast<std::chrono::milliseconds>(p.time_since_epoch()).count();
    return epoch;
}

正在从另一个method调用thread,并更新我的m_keepAlive

void Bar::keepAlive() //This method is being called from other thread
{
    m_keepAlive= getTimeSinceEpoch();
}

在我的Bar class上,我有一个方法一直调用此checkKeepAlive()方法并检查是否已经过了 2秒,因为上一次Bar::keepAlive()是执行。

void Bar::checkKeepAlive()
{
    auto now = std::chrono::system_clock::now();

   //COMPILATION ERROR here
    auto difference = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_keepAlive); 

    auto timeMsSinceNoReply = difference.count();

    if(timeMsSinceNoReply >= 2000)
    {
        //timeout
    }
}

为了完成这项工作,我已经在班上创建了std::atomic<long long> 线程安全

但是,我收到了这个编译错误:

no match for ‘operator-’ (operand types are ‘std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >’ and ‘long long int’)

如何使用duration_cast上的std::atomic<long long>

1 个答案:

答案 0 :(得分:3)

通过使用对{em>滥用库的std::chrono::duration::count的所有调用,构建chrono库是为了让您明确并输入类型。

now - m_keepAlive在您的示例中是非法的。你的编译器告诉你这个。

  • now的类型为std::chrono::system_clock::time_point
  • m_keepAlive的类型为std::atomic<long long>

即使您将m_keepAlive更改为long long,它仍然无效。

在尝试从m_keepAlive中减去now之前,您需要将std::chrono::milliseconds(m_keepAlive.load())转换为持续时间。

例如:m_keepAlive会将const auto difference = now - std::chrono::system_clock::time_point(std::chrono::milliseconds(m_keepAlive.load());保存的值解释为毫秒数。

完整表达应该是: if(difference >= std::chrono::seconds(2)) { ... }

然后使用如下: $thisEvent.append('<button class="remove">' + i + '</button>');