简体   繁体   English

线程安全计数器C ++ 11

[英]Thread safe counter c++11

I am trying to implement a int counter which is always incremented by one thread (Thread1) and always decremented by another (Thread2) . 我试图实现一个int计数器,该计数器始终由一个线程(Thread2)递增,而始终由另一个(Thread1) (Thread2)递减。

one option is to use std::atomic<int> . 一种选择是使用std::atomic<int>

Although i got another idea where i have two variables say counterIncr and counterDecr . 虽然我有另外一个想法,我有两个变量说counterIncrcounterDecr Thread1 always increments counterIncr , while Thread2 always decrements counterDecr . Thread1总是递增counterIncr ,而线程2一直递减counterDecr

And I will use the sum of (counterIncr+counterDecr) as my final result. 我将使用(counterIncr+counterDecr)和作为最终结果。

Does this have any performance advantage? 这有什么性能优势吗? Is this wait-free? 这是免费的吗?

If you need a result that is accessible at any time, using std::atomic is the correct thing to do, and if "just a counter" is all you need, std::memory_order_relaxed is sufficient, which is reasonably efficient. 如果您需要随时可访问的结果,则正确使用std::atomic是正确的选择,如果仅需要“只是一个计数器”,则std::memory_order_relaxed就足够了,这是相当有效的。
Do however note that you still have significant bus overhead, so if you do millions of increments, this may become a limiting factor. 但是请注意,您仍然有大量总线开销,因此,如果进行数百万次增量,这可能会成为限制因素。 Do not do this unless you only expect a few hundred or so increments total (in that case it doesn't matter), or unless you really need to be able to read the value any time. 除非您只希望总数增加几百个左右(在这种情况下这无关紧要),否则,除非您确实确实需要随时能够读取该值,否则不要这样做。

If you need a final result after doing many calculations, it is much, much preferrable to join the two threads (or block them, or signal the main thread that you are done and no longer writing to the counters) and have each thread update only a per-thread counter non-atomically . 如果您需要在完成许多计算后得出最终结果,则更可取的是将两个线程连接在一起(或阻塞它们,或向主线程发出信号,告知您已完成,不再写入计数器),并且仅更新每个线程一个非原子计数器。 You can use a reference or a per-reference lambda capture so the consuming thread has "easy" access to the result. 您可以使用引用或按引用的lambda捕获,以便使用线程“轻松”访问结果。
This will not hammer the bus and will run a lot faster, but of course you only have a valid result available at the end, not any time before that. 这不会使总线受到冲击,并且运行速度会快很多,但是当然,您最终只能获得有效的结果,而不是在此之前的任何时间。

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

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