Why C++ has introduced separate std::latch and std::barrier?

419 Views Asked by At

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?

1

There are 1 best solutions below

3
Dmitry Kuzminov On

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.