我有一个包含多个线程的程序,我希望它们都能以给定的时钟间隔执行异步I / O操作(主要用于限制它们)。我希望时钟尽可能精确,但我想我可以明确地设法在软件中使用精确的时钟。我不认为我想把所有的I / O对象放在忙等待线程中(从而实现固有的同步),因为想象它们中有很多它会大大降低时钟计算的性能。假设每个I / O操作都能够跟上我的时钟周期。
我想知道我是否可以在一个繁忙的循环中使用condition_variable
来为我提供尽可能高的精确计时,然后" tick"通过notify_all()
。从概念上讲,我会做什么:
class clocker
{
public:
// Methods which spawn the threads, etc...
private:
std::atomic<std::chrono::high_resolution_clock::rep> m_clockPeriod_ns;
std::atomic<size_t> m_elapsedTicks;
std::condition_variable m_tick;
std::mutex m_tickMutex;
};
while (true)
{
auto end = std::chrono::high_resolution_clock::now();
std::chrono::high_resolution_clock::duration elapsed_ns;
// busy look timer for highest possible precision.
auto start = end;
while (elapsed_ns.count() < m_clockPeriod_ns)
{
end = std::chrono::high_resolution_clock::now();
elapsed_ns = end - start;
}
// it's possible the elapsed time is long relative to the clock period IF the high res clock
// doesn't actually have enough resolution. To get around this, figure out how many 'ticks'
// should have occurred.
m_elapsedTicks.store(elapsed_ns.count() / m_clockPeriod_ns);
m_tick.notify_all();
}
while (true)
{
std::unique_lock<std::mutex> lock(m_tickMutex);
m_tick.wait(lock);
for (int i = 0; i < m_elapsedTicks.load(); ++i)
{
// Do I/O operation
}
}
我看到这种方法存在一些问题,但我并不完全确定它们的确有多重要,或者必须如何解决这些问题: