2

There are some similar questions on SO. But they only ask the question one way.

std::latch has an advantage over std::barrier that unlike latter, former can be decremented by a participating thread more than once.

std::barrier has an advantage over std::latch that unlike latter, former can be reused once the arriving threads are unblocked at a phase's synchronization point.

But my question is, why have two almost identical things in the first place? Why they decided not combine both of them into one, something like Java Phaser?

Phaser was introduced in Java7, as a more flexible option over CountDownLatch and CyclicBarrier, which were introduced in Java5. It has almost identical API as that of both former classes. (Here I took Java's example just to show that combining them is indeed possible.)

Instead of providing a single phaser class, they decided to separately provide latch and barrier, then there must be some benefit from having them separately, mostly some performance related issue. So, what is that issue precisely?

Sourav Kannantha B
  • 2,860
  • 1
  • 11
  • 35

1 Answers1

3

C++ has an principle of not paying for something that you don't use. If std::barrier can be implemented more efficient than std::latch for the case when you don't use it twice from the same thread - there is a reason to provide a more efficient idiom together with a more generic.

As for "what is that issue precisely": C++ has no virtual machine that equalizes all systems. Moreover, STL doesn't specify the exact implementation of the class. So the implementation of latch/barrier is the matter of a system, vendor or taste of the developer.

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
  • > _for the case when you don't use it twice from the same thread_ How is it effiecient? Can you explain. – Sourav Kannantha B Jul 12 '22 at 13:56
  • Another example may explain you this better: compare `std::lock_guard` and `std::unique_lock`. The latter provides you a richer API, and allows more complex use patterns. So why the standard has both? Because relaxing the requirements on `std::lock_guard` the standard allows the implementers to do it more efficiently. As the result, for the simplest cases the `std::lock_guard` is a recommended widget, and `std::unique_lock` should be used only if you need something that `std::lock_guard` doesn't offer. But technically you can use `std::unique_lock` where `std::lock_guard` is recommended. – Dmitry Kuzminov Jul 13 '22 at 16:17
  • yes, I'm not arguing against what you said. I wanted to know one example implementation where `std::barrier` can be implemented more efficiently than `std::latch`, as the former is not used from same thread twice. – Sourav Kannantha B Jul 14 '22 at 04:11