【发布时间】:2016-02-09 11:35:06
【问题描述】:
我正在尝试使用原子实现旋转线程屏障,特别是 __sync_fetch_and_add。 https://gcc.gnu.org/onlinedocs/gcc-4.4.5/gcc/Atomic-Builtins.html
我基本上想要一个替代 pthread 屏障的方法。我在一个可以并行运行大约一百个线程的系统上使用 Ubuntu。
int bar = 0; //global variable
int P = MAX_THREADS; //number of threads
__sync_fetch_and_add(&bar,1); //each thread comes and adds atomically
while(bar<P){} //threads spin until bar increments to P
bar=0; //a thread sets bar=0 to be used in the next spinning barrier
由于显而易见的原因,这不起作用(一个线程可能设置 bar=0,而另一个线程陷入无限的 while 循环等)。我在这里看到了一个实现:Writing a (spinning) thread barrier using c++11 atomics,但是它看起来太复杂了,我认为它的性能可能比 pthread barrier 差。
由于 bar 的缓存行在线程之间进行乒乓,因此预计此实现还会在内存层次结构中产生更多流量。
关于如何使用这些原子指令来制作简单的屏障有什么想法吗?此外,通信优化方案也会有所帮助。
【问题讨论】:
标签: c++ multithreading atomic compare-and-swap barrier