3 ms·
See also: std::latch vs std::barrier [1] In short (copied from that answer): * Barriers are useful when you have a bunch of threads and you want to synchronis
by quietbritishjim 5y ago
See also: std::latch vs std::barrier [1]
In short (copied from that answer):
* Barriers are useful when you have a bunch of threads and you want to synchronise across of them at once, for example to do something that operates on all of their data at once.
* Latches are useful if you have a bunch of work items and you want to know when they've all been handled, and aren't necessarily interested in which thread(s) handled them.
[1] https://stackoverflow.com/a/62631294 https://stackoverflow.com/a/62631294
- quietbritishjim 5y agoTo add to this: I don't get why C++ distinguishes a latch from a barrier. Both of them are effectively a counter with the ability to decrement that counter (in a thread safe way) and the ability to wait until the value reaches zero (or return immediately if it is already zero). The only difference is that is a latch does those things separately from different threads while a barrier does them both at once in every thread. That's even reflected in the similar method names: .count_down() and .wait() on latch, and .count_down_and_wait() on barrier. Why not make all three methods be methods of one class, which simplifies the API and potentially allows other use cases?
- nly 5y agoAlmost certainly the answer is one can be implemented more efficiently than the other using a particular API on a particular platform.
- flqn 5y agoBoth latches and barriers can be implemented with a counting semaphore sure. C++20 provides one of those too along with these abstractions.
- quietbritishjim 5y agoHow could either of them be implemented with a counting semaphore? It seems like it waits in the wrong (opposite) situation than barrier and latch need, but maybe I'm just not being imaginative enough.
- deleted 5y ago[deleted]