工作结束后,是否可以使线程加入"parallel for"区域? [英] Is it possible to make thread join to 'parallel for' region after its job?
问题描述
我有两个需要首先同时运行的工作:
I have two jobs that need to run simultaneously at first:
1)用于可并行化的循环
1) for loop that can be parallelized
2)可以用一个线程完成的功能
2) function that can be done with one thread
现在,让我描述一下我想做什么.
Now, let me describe what I want to do.
如果存在8个可用线程,
If there exist 8 available threads,
job(1)和job(2)必须首先同时具有7个线程和1个线程同时运行.
job(1) and job(2) have to run simultaneously at first with 7 threads and 1 thread, respectively.
在job(2)完成之后,应该将job(2)使用的线程分配给并行于for循环的job(1).
After job(2) finishes, the thread that job(2) was using should be allocated to job(1) which is the parallel for loop.
I'm using omp_get_thread_num to count how many threads are active in each region. I would expect the the number of threads in job(1)
increases by 1 when job(2)
finishes.
以下描述了可能是错误或确定的解决方案:
Below describes a solution that might be wrong or ok:
omp_set_nested(1);
#pragma omp parallel
{
#pragma omp sections
{
#pragma omp section // job(2)
{ // 'printf' is not real job. It is just used for simplicity.
printf("i'm single: %d\n", omp_get_thread_num());
}
#pragma omp section // job(1)
{
#pragma omp parallel for schedule(dynamic, 32)
for (int i = 0 ; i < 10000000; ++i) {
// 'printf' is not real job. It is just used for simplicity.
printf("%d\n", omp_get_thread_num());
}
}
}
}
如何使我想要完成的工作完成?
How can make the work that I want to achieve be done?
推荐答案
这样的事情怎么办?
#pragma omp parallel
{
// note the nowait here so that other threads jump directly to the for loop
#pragma omp single nowait
{
job2();
}
#pragma omp for schedule(dynamic, 32)
for (int i = 0 ; i < 10000000; ++i) {
job1();
}
}
我没有对此进行测试,但是由于nowait,单个线程将仅由一个线程执行,而所有其他线程将直接跳至for循环. 另外,我认为它比章节更容易阅读.
I did not test this but the single will be executed by only one threads while all others will jump directly to the for loop thanks to the nowait. Also I think it is easier to read than with sections.
这篇关于工作结束后,是否可以使线程加入"parallel for"区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!