【问题标题】:std::atomic<std::chrono::high_resolution_clock::time_point> can not compilestd::atomic<std::chrono::high_resolution_clock::time_point> 无法编译
【发布时间】:2015-06-04 13:05:33
【问题描述】:

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

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

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

【问题讨论】:

  • atomic 只能用于可简单复制的类型,据我所知,不能保证 time_point 可以简单复制。
  • T.C.说是对的。并且你可以使用std::is_trivial or other 测试一下...

标签: c++ multithreading c++11


【解决方案1】:

您的选择:

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

  • 选择一些整数时间单位(例如,自纪元以来的毫秒数)并即时转换为/从该时间单位转换,将整数值存储在您计算出的某种整数类型中具有足够的容量来覆盖您的日期范围处理(可能是std::atomic_ullong

  • (删除了疯狂的建议)

【讨论】:

  • 谢谢我会尝试第二种方法,比如`duration_cast(time_point.time_since_epoch()).count()`
  • 托尼,虽然你的前两个要点很好,但我不能赞成 任何 似乎暗示 UB 可以接受的最简单可能性的答案:- )
  • “拥抱未定义的行为”我喜欢这句话,我想我需要它在 T 恤上。其设计暗示了拥抱 UB 的人是多么的混蛋,总是生活在边缘。基本上是编码的基本跳线?
【解决方案2】:

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

【讨论】:

  • 你不是说std::atomic&lt;std::chrono::high_resolution_clock::rep&gt;吗?是否可以保证std::chrono::duration 可以轻松复制?
  • 即使rep 也不能保证可以轻松复制。来自eel.is/c++draft/time.duration#general 第 2 段:Rep 应为算术类型或模拟算术类型的类。
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 2020-10-13
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多