简体   繁体   English

为什么 C++20 屏障中存在单独的到达和等待?

[英]Why do separate arrive and wait exist in C++20 barrier?

C++20 std::barrier has arrive_and_wait method, which is what pretty much every synchronization barrier implementation has. C++20 std::barrier有到达和arrive_and_wait方法,几乎每个同步屏障实现都有。

But it also has separate arrive and wait .但它也有单独的arrivewait Why do these functions exist?为什么会有这些功能?

OK, so you've got a bunch of threads that have to do some kind of synchronized tasks.好的,所以你有一堆线程必须执行某种同步任务。 These tasks are grouped into phases: the tasks from one phase will use data produced by tasks from a previous phase, and all previous phase work must be done before any next-phase work can start.这些任务被分组为阶段:一个阶段的任务将使用前一阶段的任务产生的数据,并且必须先完成所有前一阶段的工作,然后才能开始任何下一阶段的工作。 Any work that requires data from a previous phase shall be called "in-phase" work.任何需要前一阶段数据的工作都应称为“同阶段”工作。

However, let's say that not everything you need to do actually requires data from a previous phase.但是,假设您需要做的所有事情实际上都需要前一阶段的数据。 There could be some individual work items that a thread could perform that doesn't read data from a previous phase.线程可能执行的某些单独的工作项不会从前一阶段读取数据。 Let's call this "out-of-phase" work.我们称之为“异相”工作。

If you try to do this out-of-phase work before calling arrive_and_wait , then you could be blocking all of the other threads from doing something even through you are done with the actual work they're waiting on.如果您在调用arrive_and_wait之前尝试执行此异相工作,那么即使您完成了它们正在等待的实际工作,您也可能会阻止所有其他线程执行某些操作。 Depending on the balance between in-phase and out-of-phase work, that could be a lot of wasted performance.根据同相和异相工作之间的平衡,这可能会浪费很多性能。

So if a thread has finished its in-phase work and has some out-of-phase work to do, it can arrive .所以如果一个线程已经完成了它的同相工作并且有一些异相工作要做,它就可以arrive This potentially frees up all of the other threads if they too are finished with their in-phase work.如果其他线程也完成了同相工作,这可能会释放所有其他线程。 The thread can then go process some out-of-phase work potentially asynchronously with work being done from the next phase.然后,该线程可以 go 处理一些可能与下一阶段正在完成的工作异步的异相工作。 Once the out-of-phase work is done, the thread can wait on the token generated by its call to arrive , which if the next phase has started, will return without blocking.一旦异相工作完成,线程可以wait其调用生成的令牌arrive ,如果下一个阶段已经开始,它将返回而不阻塞。

Indeed, if the amount of in-phase work is much less than the amount of out-of-phase work, then this pattern means that threads almost never block.实际上,如果同相工作量远小于异相工作量,那么这种模式意味着线程几乎从不阻塞。 The barrier just acts as a multi-thread atomic ordering operation, never a blocking one.屏障仅充当多线程原子排序操作,而不是阻塞操作。

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

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