简体   繁体   English

原子加法运算与多线程多变量(C中)

[英]Atomic addition operations vs multiple variables with multithreading (in C)

When considering performance as the only factor, for extremely fast addition in a multithreaded context, is it better to use the GCC builtin sync / atomic operations to add to a single variable, or is it more performant to add to a single counter per thread? 当考虑性能是唯一因素时,对于多线程上下文中的极快添加,使用GCC内置同步/原子操作添加到单个变量更好,还是每个线程添加到单个计数器更高效?

For example, if I have 8 threads, where a total count of processed items must be incremented (at an extremely high rate), would it be better to have a single variable and increment it from each thread using the atomic operations, or would it be better to have 8 separate variables, one for each thread, and then aggregate the data from the 8 variables at some interval? 例如,如果我有8个线程,其中处理项的总数必须递增(以极高的速率),是否更好的是使用单个变量并使用原子操作从每个线程递增它,或者它是否会更好最好有8个单独的变量,每个线程一个,然后以某个间隔汇总来自8个变量的数据?

It would most likely be much faster for each thread to do its work separately and then aggregate it at the end. 每个线程分别完成其工作然后在最后聚合它可能会快得多。 ADD instructions are some of the simplest in the instruction set and run very quickly (~1 clock cycle). ADD指令是指令集中最简单的指令,运行速度非常快(约1个时钟周期)。 The overhead to lock a mutex or similar would be larger than the actual computation. 锁定互斥锁或类似物的开销将大于实际计算。 Perhaps more importantly, if it's not shared the counter can reside in a register instead of in main memory which is also significantly faster. 也许更重要的是,如果没有共享,计数器可以驻留在寄存器中而不是主存中,这也明显更快。

In general, it's both faster and easier to avoid sharing state unless you have to. 通常,除非必须,否则更快更容易避免共享状态。

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

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