高效的内存屏障 [英] Efficient Memory Barriers
问题描述
我有一个多线程应用程序,其中每个线程都有一个整数类型的变量.这些变量在程序执行期间增加.在代码的某些点,一个线程将其计数变量与其他线程的计数变量进行比较.
I have a multithreaded application, where each thread has a variable of integer type. These variables are incremented during execution of the program. At certain points in the code, a thread compares its counting variable with those of the other threads.
现在,由于我们知道在多核上运行的线程可能会无序执行,因此一个线程可能无法读取其他线程的预期计数器值.为了解决这个问题,一种方法是使用原子变量,例如C ++ 11的std :: atomic<>.但是,在每个计数器增量处执行内存隔离会大大降低程序的速度.
Now since, we know that threads running on multicore might execute out of order, a thread might not read the expected counter values of the other threads. To solve this problem, one way is to use atomic variable, such as std::atomic<> of C++11. However, performing a memory fence at each increment of counters will significantly slow down the program.
现在我要做的是,当一个线程将要读取其他线程的计数器时,仅创建一个内存隔离,然后在内存中更新所有线程的计数器.如何用C ++做到这一点.我正在使用Linux和g ++.
Now what I want to do is that when a thread is about to read other thread's counter, only then a memory fence is created and counters of all the threads are updated in the memory at that point. How can this be done in C++. I am using Linux and g++.
推荐答案
C ++ 11标准库包括对<atomic>
和std::atomic_thread_fence
中的篱笆的支持.
The C++11 standard library includes support for fences in <atomic>
with std::atomic_thread_fence
.
调用此方法会调用完整的篱笆:
Calling this invokes a full fence:
std::atomic_thread_fence(std::memory_order_seq_cst);
如果您只想发射获取或释放栅栏,则可以使用std:memory_order_acquire
和std::memory_order_release
代替.
If you want to emit only an acquire or only a release fence, you can use std:memory_order_acquire
and std::memory_order_release
instead.
这篇关于高效的内存屏障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!