即使在多核环境中,也有std :: chrono线程安全性保证吗? [英] Is there any std::chrono thread safety guarantee even with multicore context?
问题描述
首先,我假设调用std :: chrono的任何函数都保证是线程安全的(没有不确定的行为或竞争条件,或者如果从不同的线程调用则不会有任何危险).我说得对吗?
First, I'm assuming that calling any function of std::chrono is guaranteed to be thread-safe (no undefined behaviour or race conditions or anything dangerous if called from different threads). Am I correct?
接下来,例如在Windows上,存在一个与多核处理器有关的众所周知的问题,该问题迫使与时间相关的系统的一些实现,以允许强制特定内核获取任何时间信息
Next, for example on windows there is a well known problem related to multi-core processors that force some implementations of time related systems to allow forcing a specific core to get any time information.
我想知道的是:
- 在标准中使用std :: chrono,是否可以保证不会出现思考问题?
- 还是实现定义了
- 或者是否明确缺乏保证,暗示您最好在Windows上始终从同一内核获取时间?
推荐答案
是的,从不同线程调用 some_clock :: now()
应该是线程安全的.
Yes, calls to some_clock::now()
from different threads should be thread safe.
关于您在 QueryPerformanceCounter
中提到的特定问题,仅仅是Windows API在某些平台上暴露了硬件问题.其他操作系统可能会也可能不会将此硬件问题暴露给用户代码.
As regards the specific issue you mention with QueryPerformanceCounter
, it is just that the Windows API exposes a hardware issue on some platforms. Other OSes may or may not expose this hardware issue to user code.
就C ++标准而言,如果时钟声称是稳定时钟",则它绝不能向后退,因此,如果同一线程上有两次读取,则第二个绝不能返回早于该值的值.首先,即使操作系统将线程切换到其他处理器.
As far as the C++ standard is concerned, if the clock claims to be a "steady clock" then it must never go backwards, so if there are two reads on the same thread, the second must never return a value earlier than the first, even if the OS switches the thread to a different processor.
对于非稳定时钟(例如,在许多系统上为
For non-steady clocks (such as std::chrono::system_clock
on many systems), there is no guarantee about this, since an external agent could change the clock arbitrarily anyway.
使用我对C ++ 11线程库的实现(包括 std::chrono
的东西)的实现要注意确保稳定的时钟确实是稳定的.这样做确实要比对 QueryPerformanceCounter
的原始调用要多得多,以确保同步,但是不再将线程固定到CPU 0(它曾经这样做).我希望其他实现也可以解决此问题.
With my implementation of the C++11 thread library (including the std::chrono
stuff) the implementation takes care to ensure that the steady clocks are indeed steady. This does impose a cost over and above a raw call to QueryPerformanceCounter
to ensure the synchronization, but no longer pins the thread to CPU 0 (which it used to do). I would expect other implementations to have workarounds for this issue too.
稳定时钟的要求在20.11.3 [time.clock.req](C ++ 11标准)中
The requirements for a steady clock are in 20.11.3 [time.clock.req] (C++11 standard)
这篇关于即使在多核环境中,也有std :: chrono线程安全性保证吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!