我可以在OpenMP分配多个线程到一个代码段
Can I assign multiple threads to a code section in OpenMP?
我正在寻找一种方法来并行执行代码的部分使用多个线程为每个部分。例如,如果我有16个线程和两个任务,我想要8个线程同时执行这两个任务。OpenMP有几个并行执行一般代码的结构(section
, task
),但它们是单线程的。在我的场景中,使用section
或task
将导致一个线程分别执行两个任务,而14个线程闲置。
这样的事情在OpenMP中是可能的吗?如果有,我该怎么做,如果没有,我可以用什么来达到这个目的?
谢谢你的时间!
编辑2:
让我用一个示例代码展开这个问题:
class some_class{
void task(){
cout<<"Entering the task method"<<endl;
#pragma openmp parallel for
for(int i=0; i < large_matrix.rows(); i++){
perform_thread_safe_operation(large_matrix.getRow(i));
}
}
matrix large_matrix;
};
void main(){
//I have 16 cores, so I want to spawn 16 threads
some_class o1;
some_class o2;
// I want 8 of the 16 threads to execute this line:
o1.task();
// and 8 remaining threads to execute this line:
o2.task();
}
您可以使用嵌套的并行区域来做到这一点。
omp_set_nested(1);
#pragma omp parallel num_threads(2)
{
if (omp_get_thread_num() == 0){
#pragma omp parallel num_threads(8)
{
// Task 0
}
}else{
#pragma omp parallel num_threads(8)
{
// Task 1
}
}
}
或者,你可以这样做:
#pragma omp parallel num_threads(16)
{
if (omp_get_thread_num() < 8){
// Task 0
}else{
// Task 1
}
}
注意,如果OpenMP决定使用少于16个线程,此代码将无法工作。您必须为此插入您自己的清理代码。
编辑:回应你的更新:
class some_class{
void task(){
cout<<"Entering the task method"<<endl;
#pragma omp parallel for num_threads(8)
for(int i=0; i < large_matrix.rows(); i++){
perform_thread_safe_operation(large_matrix.getRow(i));
}
}
matrix large_matrix;
};
void main(){
omp_set_nested(1);
//I have 16 cores, so I want to spawn 16 threads
some_class o1;
some_class o2;
#pragma omp parallel num_threads(2)
{
if (omp_get_thread_num() == 0){
// I want 8 of the 16 threads to execute this line:
o1.task();
}else{
// and 8 remaining threads to execute this line:
o2.task();
}
}
}
相关文章:
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 在Qt/C++中从一个代码构建两个略有不同的项目
- 编写一个代码,使年利率翻倍
- G++ 发出警告,要求删除一个代码的数组,但不删除另一个代码的数组
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 我想制作一个代码,将C 中的单个数字值分开.例如:12345 = 1 2 3 4 5
- 我已经编写了一个代码来查找数组元素的反向,但它没有给出所需的输出
- 循环在此代码中仅迭代一次,而在另一个代码中正确迭代
- 我需要编写一个代码,从用户那里获取输入(句子)并停止在@处
- 我试图编写一个代码来查找一个单词是否是回文,但它不起作用。怎么了?
- 我不知道为什么只有一个代码在两个代码之间具有sigsegv(看起来相同)
- 编写一个代码,该代码在给定的链表中将删除具有奇数值的元素
- 查找哪个代码段比另一个代码段快
- 我正在编写一个代码,该代码从用户那里为公司中的五个项目输入数量
- 如果我制作一个代码,每个线程都会修改数组的完全不同的部分,则将保持缓存相干性
- 为什么下一个代码不编译
- 卡在测试'if':另一个代码的一部分
- 我有一个 c++ 代码,它在启动时崩溃,然后到达问题所在 main() 的执行
- C++语法谁呼吁一个代码块-简化工作
- 两个类相互包含,下一个代码有什么问题?