OpenMP如何重用线程 [英] How does OpenMP reuse threads

查看:122
本文介绍了OpenMP如何重用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为创建和删除线程可能会很昂贵. OpenMP是否尝试重用现有线程?例如,

I assume thread creation and deletion could be costly. Does OpenMP try reuse existing threads? For example,

#pragma omp parallel sections num_threads(4)
   {
    #pragma omp section
    { ... worker A ... }
    #pragma omp section
    { ... worker B ... }
   }
   #pragma omp parallel sections num_threads(4)
   {
    #pragma omp section
    { ... worker C ... }
   #pragma omp section
   { ... worker D ... }
  }

在执行过程中,OpenMP是分配5个线程还是3个线程(C和D重用了A和B使用的线程)?

In execution, does OpenMP allocate 5 threads or 3 (in which C and D reuse the threads that A and B used)?

推荐答案

在您的示例中,将在输入第一个并行部分时创建/激活一个由4个工作"线程组成的团队,其中两个将在做一些工作:一个正在做A,另一个正在做B.另外两个将在本节结尾处闲置.然后,在该部分退出时销毁/停用这4个线程.然后,在进入第二个并行部分时将创建/激活一个由4个线程组成的新团队,并且将发生同样的事情...现在我说了created/activated,因为正如您所猜测的那样,创建线程的成本很高,因此该标准允许编译器创建线程一次,并且仅在需要时才让线程在并行部分之间休眠.但这是一个实现细节,对于程序员来说应该是透明的.

In your example, a team of 4 "working" threads will be created/activated upon entry of your first parallel section, and 2 of them will be doing some work: one doing A and another doing B. The 2 others will be waiting idle at the end of the section. The 4 threads are then destroyed/deactivated upon exit of the section. Then a new team of 4 threads will be created/activated upon entry of the second parallel section and the same will happen... Now I said created/activated because since as you guessed, creating threads is costly, the standard allows compilers to create threads once and to only put threads to sleep between parallel sections if they want. But this is an implementation detail that should be transparent for the programmer.

在一天结束时,无法知道哪个线程将处理A,B,C和D ...您只能确定A和B将由2个不同的线程处理,并且C和D也有两个不同的线程.

At the end of the day, there's no way of knowing which thread will deal with A, B, C and D... You can only be sure that A and B will be handled by 2 different threads and that C and D by two different threads as well.

这篇关于OpenMP如何重用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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