简体   繁体   English

旋转等待C ++ 11

[英]Spin wait C++11

I have the following struct 我有以下结构

struct info {
 unsigned long a;
 unsigned long b;
};

atomic <info> data;

used by a writer thread and a reader thread. 由作者线程和读者线程使用。 The reader has to respond to the new values as fast as possible. 读者必须尽快响应新值。 To do that I've implemented the following in the reader : 为此,我在读者中实现了以下内容:

while (true) {
  auto value = data.load();
  // do some operations given these new values
}

This operation is very processor intensive. 此操作非常耗费处理器资源。 I've opted for this method because I believe it's faster than, for example, using a condition variable and then waiting for the reader thread to be awakened when data changes. 我之所以选择这种方法,是因为我认为它比例如使用条件变量然后等待数据更改时唤醒阅读器线程要快。 Also, the data updates quite frequently, hundreds of times per second. 而且,数据更新非常频繁,每秒数百次。 Is there a better way to do this while still having the fastest reaction time? 有没有更好的方法来做到这一点,同时仍具有最快的反应时间?

A semaphore is indeed a good option to let a writer signal new data, while a reader wakes up whenever data is ready to be consumed. 信号量确实是使写入器发出新数据信号的好选择,而读取器则在准备好使用数据时会醒来。 However, for high performance scenarios you should consider a lock-free queue, like the one written by Moody Camel . 但是,对于高性能场景,您应该考虑使用无锁队列,例如Moody Camel编写的队列。 Such a queue allows writers to add new data entries without blocking the reader(s) and the reader can get data as fast as possible, without blocking the writer(s). 这样的队列使编写者可以添加新的数据条目而不会阻塞读取器,并且读取器可以在不阻塞写入器的情况下尽可能快地获取数据。 That way data can be processed at maximum speed, if it is available and don't consume CPU resources otherwise. 这样,如果可用的话,数据就可以以最快的速度处理,否则就不消耗CPU资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM