openmp中的任务(task)

本文介绍了并行程序中任务的概念,如何使用omp指令创建和管理任务,以及single子句在控制任务执行顺序和避免重复任务中的作用。特别强调了single如何在循环中创建任务并放入任务池,以及线程之间的协作和同步过程。
摘要由CSDN通过智能技术生成

一、Task概念

Tasks are composed of:
– code to execute
– data environment
– internal control variables (ICV)

并行程序会用一个线程按照程序代码的顺序生成任务; 在不附加何限制的情况下, 这些任务将放入到任务池中, 由空闲的线程取出执行, 如上图所示。换言之, 任务的默认执行顺序是未指定的、随机的。

指令task 主要适用于不规则的循环迭代(如do while) 和递归的函数调用, 这些都是无法利用指令for 完成的情况。

二、任务的创建

1、指令parallel和子句single

 为了避免一个任务被重复地定义, 需要single 子句, 如下例所示。

一般而言, 通常使用指令single 利用一个线程创建任务(single 子句保证只有一个线程进行创建任务)。这些任务在创建后, 将被放入到任务池, 供线程组中空闲的线程获取和执行。

1.1 如何理解parallel区块中用single,然后再在single中使用task创建任务

参考c++ - How do "omp single" and "omp task" provide parallelism? - Stack Overflow回答

1

2

3

4

5

6

7

8

9

10

11

1  #pragma omp parallel

2  {

3      #pragma omp single

4      {

5          for(node* p = head; p; p = p->next)

6          {

7              #pragma omp task

8              process(p);

9          }

10     } // barrier of single construct

11 }

In the code, I have marked a barrier that is introduced at the end of the single construct.

What happens is this:

First, when encountering the parallel construct, the main thread spawns the parallel region and creates a bunch of worker threads. Then you have n threads running and executing the parallel region.

Second, the single construct picks any one of the n threads and executes the code inside the curly braces of the single construct. All other n-1 threads will proceed to the barrier in line 10. There, they will wait for the last thread to catch up and complete the barrier synchronization. While these threads are waiting there, they are not only wasting time but also wait for work to arrive. 

Third, the thread that was picked by the single construct (the "producer") executes the for loop and for each iteration it creates a new task. This task is then put into a task pool so that another thread (one of the ones in the barrier) can pick it up and execute it. Once the producer is done creating tasks, it will join the barrier and if there are still tasks in the task pool waiting for execution, it will help the other threads execute tasks.

Single选中的那个线程会在for循环中不停地创建任务,每一次循环就创建一个任务,这个任务被放入线程池(注意!!这个任务不是被single的这个线程执行,而是先被放入任务池)。其它的n-1个线程就会去执行。

Fourth, once all tasks have been generated and executed that way, all threads are done and the barrier synchronization is complete.

1.2 示例

        

  • 22
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一百编程网朱老师

谢谢大爷谢谢大爷谢谢大爷谢谢大

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值