2015-03-31 73 views
9

我需要std::chrono::high_resolution_clock::time_point字段,我想从一个线程写入并从另一个线程读取。如果我声明它是我的代码编译没有任何错误。std :: atomic <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场,我从一个线程读写从另一个(以确保“阅读线程”看到最后一个值)?

+5

'atomic'只能与普通可复制类型一起使用,并且据我所知,不能保证'time_point'是可以复制的。 – 2015-03-31 09:05:11

+0

T.C.说的是对的。你可以使用[std :: is_trivial或其他](http://en.cppreference.com/w/cpp/types/is_trivial)测试它... – 2015-03-31 09:08:35

回答

8

您的选择:

  • 忘记使其原子,并使用互斥连载访问

  • 挑一些时间整体单元(例如因为毫秒为单位),并转换到/从上苍蝇,将积分值存储在您已经计算出的某种整数类型中,具有足够的容量来覆盖您正在处理的日期范围(可能为std::atomic_ullong

  • [for completeness/not recommend nded]如果你的执行情况直接在物体保持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();

+0

谢谢我会尝试第二种方法,像'duration_cast ( time_point.time_since_epoch())。count()' – javapowered 2015-03-31 10:18:06

+0

Tony,虽然你的前两个项目符合要求,但我无法对任何*回答看起来暗示着UB可能被接受的最可能的可能性:-) – paxdiablo 2017-11-21 00:15:38

4

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

相关问题