What is the fastest way to send data from one thread to another in C++?

蹲街弑〆低调 提交于 2019-12-04 06:43:48

I imagine your latency is a product of how the operating system schedules context-switching, rather than the spin lock itself, and I doubt you can do much about it.

You can, however, move more data at once by using a ring buffer. If one thread writes and one thread reads, you can implement a ring buffer without locks. Essentially it would be the same spin-lock approach (waiting until tailidx != headidx), but the producer could pump more than a single value into the buffer before it is switched out to the consumer. That ought to improve your overall latency (but not your single-value latency).

If your threads are executed on different cores, then the fastest way to "send message" from one thread to another is write barrier(sfence).

When you write to some memory location, you actually write to the processors write buffer, not to the main-memory location. Write buffer is periodically flushed to main memory by the processor. Also, write instruction can be delayed when instruction reordering occurs. When actual write to main memory occurs, cache coherency protocol comes into play and "informs" another processor about memory location update. After that, another processor invalidates cache line and another thread will be able to see your changes.

Store barrier force processor to flush write buffer and prohibit instruction reordering and your program will be able to send more messages per second.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!