为什么C ++ 20障碍中存在单独到达和等待? [英] Why do separate arrive and wait exist in C++20 barrier?

查看:83
本文介绍了为什么C ++ 20障碍中存在单独到达和等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 20 std :: barrier 具有 arrive_and_wait 方法,几乎​​每个同步屏障实现都具有这种方法。

C++20 std::barrier has arrive_and_wait method, which is what pretty much every synchronization barrier implementation has.

分别有到达等待。为什么存在这些功能?

But it also has separate arrive and wait. 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.

如果您在调用 arrive_and_wait 之前尝试执行此阶段的工作,则可能会阻止所有其他线程甚至通过您执行的操作都由他们正在等待的实际工作完成。取决于同相和异相工作之间的平衡,这可能是很多浪费的性能。

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. 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. 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. 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.

实际上,如果同相工作量小于异相工作量,则这种模式意味着线程几乎 never 处于阻塞状态。屏障只是充当多线程原子排序操作,而绝不会成为阻塞操作。

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.

这篇关于为什么C ++ 20障碍中存在单独到达和等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆