std::atomic<std::chrono::high_resolution_clock::time_point> 无法编译

std::atomic<std::chrono::high_resolution_clock::time_point> can not compile

本文关键字:std gt point 编译 time resolution lt chrono high atomic clock      更新时间:2023-10-16

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

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

/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字段(以确保"读取线程"看到最后一个值)?

您的选择:

  • 忘记让它成为原子,使用互斥体串行访问

  • 选择一些积分的时间单位(例如,自epoch以来的毫秒),并在运行中转换为该时间单位,将积分值存储在您计算出的某个积分类型中有足够的容量来覆盖您处理的日期范围(可能是std::atomic_ullong

  • (删除了疯狂的建议)

存储时使用std::atomic<std::chrono::high_resolution_clock::duration>并将其设置为time_point::time_sance_epoch();加载时,使用标准转换构造函数从原子中的持续时间构造一个时间点。这是必要的,这有点令人恼火,但至少它是类型安全的,并且原子类型的大小或分辨率没有不确定性。