OpenMP:递归细分工作和线程
OpenMP: recursively subdividing work and threads
我想知道如何使用 OpenMP 编写以下逻辑:
do_something(Job job, Threads x ... x+b){
if(b<1) // if only one thread is assigned
do_real_work(job); return;
// otherwise, divide the work in two subtasks
// Only one thread executes this:
Divide job into job1 and job2
// Divide the assigned threads into two groups
// and assign the subtasks to them.
// The below two lines should be executed in parallel.
do_something(job1, x ... x+b/2)
do_something(job2, x+b/2 ... x+b)
}
上述工作流程本身就是简单的分而治之。我想以 "binary-tree" 的方式将工作分配给 n 个线程。
特别是,我希望程序能够从 evn var 中获取线程数,并递归地处理除法。
如果使用4个线程,则执行两级;
如果使用8个线程,则执行三个级别等
我不知道如何在 OpenMP 中指定线程子集来执行并行任务。
甚至可以指定线程 ID 来执行任务吗?
虽然可以通过omp_get_thread_num()
获取线程ID,并根据该ID进行分支,但您的问题似乎更适合使用显式任务来解决。环境变量 OMP_NUM_THREADS
中设置的最大 OpenMP 线程数可以通过调用 omp_get_max_threads()
获得(即使在并行区域之外),实际数量可以通过在并行区域中调用 omp_get_num_threads()
获得活动区域。并行代码应该类似于:
do_something(Job job, Threads x ... x+b){
if(b<1) // if only one thread is assigned
do_real_work(job); return;
// otherwise, divide the work in two subtasks
// Only one thread executes this:
Divide job into job1 and job2
// Divide the assigned threads into two groups
// and assign the subtasks to them.
// The below two lines should be executed in parallel.
#pragma omp task
do_something(job1, x ... x+b/2)
#pragma omp task
do_something(job2, x+b/2 ... x+b)
}
// Call like follows
#pragma omp parallel
{
#pragma omp single
{
b = omp_get_num_threads();
do_something(job, x, b);
}
}
我想知道如何使用 OpenMP 编写以下逻辑:
do_something(Job job, Threads x ... x+b){
if(b<1) // if only one thread is assigned
do_real_work(job); return;
// otherwise, divide the work in two subtasks
// Only one thread executes this:
Divide job into job1 and job2
// Divide the assigned threads into two groups
// and assign the subtasks to them.
// The below two lines should be executed in parallel.
do_something(job1, x ... x+b/2)
do_something(job2, x+b/2 ... x+b)
}
上述工作流程本身就是简单的分而治之。我想以 "binary-tree" 的方式将工作分配给 n 个线程。 特别是,我希望程序能够从 evn var 中获取线程数,并递归地处理除法。 如果使用4个线程,则执行两级; 如果使用8个线程,则执行三个级别等
我不知道如何在 OpenMP 中指定线程子集来执行并行任务。 甚至可以指定线程 ID 来执行任务吗?
虽然可以通过omp_get_thread_num()
获取线程ID,并根据该ID进行分支,但您的问题似乎更适合使用显式任务来解决。环境变量 OMP_NUM_THREADS
中设置的最大 OpenMP 线程数可以通过调用 omp_get_max_threads()
获得(即使在并行区域之外),实际数量可以通过在并行区域中调用 omp_get_num_threads()
获得活动区域。并行代码应该类似于:
do_something(Job job, Threads x ... x+b){
if(b<1) // if only one thread is assigned
do_real_work(job); return;
// otherwise, divide the work in two subtasks
// Only one thread executes this:
Divide job into job1 and job2
// Divide the assigned threads into two groups
// and assign the subtasks to them.
// The below two lines should be executed in parallel.
#pragma omp task
do_something(job1, x ... x+b/2)
#pragma omp task
do_something(job2, x+b/2 ... x+b)
}
// Call like follows
#pragma omp parallel
{
#pragma omp single
{
b = omp_get_num_threads();
do_something(job, x, b);
}
}