OpenMP - 编译制导(二)- section、single

section制导

OpenMP中的section子句是用于在sections子句内部将代码划分成几个不同的段。当与#pragma omp parallel sections结合使用时,这些代码段会并行处理。每个section由其中的一个线程执行一次,不同的section可以由不同的线程执行。当然,如果一个线程运行得足够快,它可能会执行多个sectionOpenMP运行时库会负责将线程分配给各个section

#include <iostream>
#include <omp.h>
using namespace std;

int main(int argc, char* argv[]){
    int a[5];
    #pragma omp parallel sections
    {
        #pragma omp section
        {
            a[0] = omp_get_thread_num();
        }
        #pragma omp section
        {
            a[1] = omp_get_thread_num();
        }
        #pragma omp section
        {
            a[2] = omp_get_thread_num();
        }
        #pragma omp section
        {
            a[3] = omp_get_thread_num();
        }
        #pragma omp section
        {
            a[4] = omp_get_thread_num();
        }
    }

    for (int i = 0; i < 5; ++i) {
        cout << "section " << i << " -> " << "thread " << a[i] << endl;
    }
    return 0;
}
section
 section 0 -> thread 0
section 1 -> thread 0
section 2 -> thread 1
section 3 -> thread 2
section 4 -> thread 3
section 6 thread 4
 section 0 -> thread 0
section 1 -> thread 0
section 2 -> thread 1
section 3 -> thread 1
section 4 -> thread 2
section 5 -> thread 3
section 2 thread 4
 section 0 -> thread 0
section 1 -> thread 1

single制导

#pragma omp single用于指定紧随其后的代码块在当前并行域中只被一个线程执行。即使存在多个线程,也只有其中一个线程会执行该代码块,而其他线程则会跳过该代码块。这个指令在并行区域内部使用,用于确保某些代码只被执行一次,无论有多少个线程参与并行执行。这对于初始化共享变量、设置锁、执行单线程任务等情况非常有用。

#include <iostream>
#include <omp.h>
using namespace std;

int main(int argc, char* argv[]){
    #pragma omp parallel
    {
        cout << "thread " << omp_get_thread_num() << endl;
        #pragma omp single
        {
            cout << "is single on thread " << omp_get_thread_num() << endl;
        }
    }
    return 0;
}
single
 thread thread thread 210


is single on thread 2
thread 3

。。

 

posted @ 2024-03-11 13:47  酥炸小黄瓜  阅读(238)  评论(0)    收藏  举报