如果存在std :: barrier,为什么要使用std :: latch?

如果存在std :: barrier,为什么要使用std :: latch?

问题描述:

从文档中可以很明显地看出它们之间的区别在于 std:: barrier 可以多次使用,并且 std :: latch 只能使用一次.

From the documentation is pretty clear that the difference between them is that std::barrier can be used more than once and std::latch can only be used once.

在我看来, std :: latch 只是 std :: barrier 的特例,它添加了限制而不是功能.最重要的是,文档说,对 count_down 的调用比内部计数器大的 n 是未定义的行为,因此必须以编程方式强制执行此限制.

That sounds to me like std::latch is simply a special case of std::barrier that adds a limitation instead of a feature. On top of that the documentation says that a call to count_down with an n greater than the internal counter is undefined behavior, so this limitation has to be enforced programatically.

那为什么我们需要 std :: latch ?

我唯一的猜测是,可以在硬件级别上以不同的方式实现 std :: latch 的方式,从而提高性能.

My only guess is that it is possible to implement std::latch differently at the hardware level in a way that improves performance.

原因是什么?

在API方面, std :: latch 可让您倒计时而不会阻塞.想象一下,您必须在开始其他一些任务之前渲染172个问题.您可以设置一个值为173的锁存器,并让每个完成故障的线程都向下计数该锁存器,并让应该消耗这些故障的线程在锁存器上等待.

API wise, std::latch lets you count down without blocking. Imagine you have to render 172 furbles before some other task starts. You can set up a latch with a value of 173, and have each thread that completes a furble count down the latch, and have the thread that is supposed to consume those furbles wait on the latch.

工作线程将递减计数,但不要等待,因为它们还有其他问题要渲染.如果他们入睡,他们会使用其他一些同步原语来实现.

The worker threads will count down, but not wait as they have other furbles to render. If they go to sleep, they'd use some other synchronization primitive to do it.

std :: barrier 仅允许您在阻止时倒计时.它不能用于允许10个线程渲染172个问题.作为障碍物上的线索,您唯一可以做的就是达到目标,或者确定您不再参与其中.

std::barrier only lets you count down while blocking. It could not be used to permit 10 threads to render 172 furbles. The only thing you can do as a thread on a barrier is to reach it, or decide you aren't participating anymore.

可能还存在硬件差异,但是它们的API完全不同,并且不可能用barrier代替闩锁.

There may also be hardware differences, but their APIs are quite different and replacing latch use with barriers is not possible.