std :: atomic< std :: chrono :: high_resolution_clock :: time_point>无法编译 [英] std::atomic<std::chrono::high_resolution_clock::time_point> can not compile

查看:168
本文介绍了std :: atomic< std :: chrono :: high_resolution_clock :: time_point>无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要std::chrono::high_resolution_clock::time_point字段,我想从一个线程写入并从另一个线程读取.如果我按原样声明它,我的代码将编译而没有任何错误.

I need std::chrono::high_resolution_clock::time_point field which I want to write from one thread and read from another thread. If I declare it as is my code compiles without any errors.

但是要使我的字段在另一个线程中可见,我像这样的std::atomic<std::chrono::high_resolution_clock::time_point>一样用std::atomic包围了它,现在出现以下编译错误:

But to make my field visible in another thread I surround it with std::atomic like this std::atomic<std::chrono::high_resolution_clock::time_point> and now I have following compilation error:

/usr/include/c++/4.8/atomic:167:7: error: function ‘std::atomic<_Tp>::atomic() [with _Tp = std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >]’ defaulted on its first declaration with an exception-specification that differs from the implicit declaration ‘constexpr std::atomic<std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > > >::atomic()’
       atomic() noexcept = default;

我应该如何声明从一个线程写入并从另一个线程读取的std::chrono::high_resolution_clock::time_point字段(以确保读取线程"看到的是最后一个值)?

How should I declare std::chrono::high_resolution_clock::time_point field which I write from one thread and read from another (to make sure that "reading thread" sees last value)?

推荐答案

您的选择:

  • 忘记让它成为原子的并使用互斥锁来序列化访问

  • forget about making it atomic and use a mutex to serialise access

选取一些整数时间单位(例如,自历元以来的毫秒数)并即时转换为该整数,从您计算出的某种整数类型中存储该整数值就足以覆盖日期范围您正在处理(也许是std::atomic_ullong)

pick some integral unit of time (e.g. milliseconds since epoch) and convert to/from that on the fly, storing the integral value in some integral type you've worked out has sufficient capacity to cover the range of dates you're handling (perhaps std::atomic_ullong)

[出于完整性/不建议使用],如果您的实现碰巧将time_point值直接保留在对象中,则可以采用 未定义的行为 并希望相同大小的整数类型可以存储time_point,复制ala std::atomic_ullong x; x.store(*reinterpret_cast<unsigned long long*>(&my_time_point));/*reinterpret_cast<unsigned long long*>(&my_time_point) = x.load();

[for completeness / not recommended] if your implementation happens to keep the time_point value directly in the object, you could embrace undefined behaviour and hope that an integral type of the same size can store time_point, copying ala std::atomic_ullong x; x.store(*reinterpret_cast<unsigned long long*>(&my_time_point)); / *reinterpret_cast<unsigned long long*>(&my_time_point) = x.load();

这篇关于std :: atomic&lt; std :: chrono :: high_resolution_clock :: time_point&gt;无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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