std::atomic<std::chrono::high_resolution_clock::time_point>无法编译 [英] std::atomic&lt;std::chrono::high_resolution_clock::time_point&gt; can not compile
问题描述
我需要 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::atomic<std::chrono::high_resolution_clock::time_point>代码>,现在我有以下编译错误:
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
)
(删除了愚蠢的建议)
这篇关于std::atomic<std::chrono::high_resolution_clock::time_point>无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!