OpenMP学习摘录
作者:互联网
摘录归纳内容来自helloacm网站
1. Hello World 模式
#include <stdio.h> int main() { #pragma omp parallel { printf("https://helloacm.com\n"); }
printf("program is ending..."); return 0; }
注1:编译指令 gcc -O2 -o xxx.exe xxx.c -fopenmp
注2:花括号内的代码运行次数与CPU核心数相同。
2. 指定并行线程个数
#include <stdio.h> int main() { #pragma omp parallel num_threads(3) { printf("https://helloacm.com\n"); } return 0; }
注1:花括号内的代码运行次数 = 3
3. 并行线程数可动态设定
#include <stdio.h> int main() { int x = 1; int y = x + 2; #pragma omp parallel num_threads(y * 3) { printf("https://helloacm.com\n"); } return 0; }
4. 获得并行线程总数/当前线程ID
#include <stdio.h> #include <omp.h> int main() { #pragma omp parallel num_threads(3) { int id = omp_get_thread_num(); int data = id; int total = omp_get_num_threads(); printf("Greetings from process %d out of %d with Data %d\n", id, total, data); } printf("parallel for ends.\n"); return 0; }
注1:这里需要导入头文件omp.h
注2:omp花括号内的变量为局部线程变量,多线程有多个拷贝。
#include <stdio.h> #include <omp.h> int main() { int data; #pragma omp parallel num_threads(3) { int id = omp_get_thread_num(); data = id; // threads may interleaving the modification int total = omp_get_num_threads(); printf("Greetings from process %d out of %d with Data %d\n", id, total, data); } printf("parallel for ends.\n"); return 0; }
注1:上面这段代码存在问题,多个线程在修改同一个全局变量data!!
#include <stdio.h> #include <omp.h> int main() { int data, id, total; // each thread has its own copy of data, id and total. #pragma omp parallel private(data, id, total) num_threads(6) {
printf("local data=%d\n", data); id = omp_get_thread_num(); total = omp_get_num_threads(); data = id; printf("Greetings from process %d out of %d with Data %d\n", id, total, data); }
printf("data=%d, id=%d, total=%d\n", data, id, total); printf("parallel for ends.\n"); return 0; }
注1:输出全是0,因为没有代码修改过这些全局变量。
注2:实际上这段代码与之前第一段代码毫无区别,线程私有变量虽与全局变量同名,但即便是在进入omp线程时,同名私有变量也没有拷贝共有变量的数值。
5. 临界区
#include <stdio.h> #include <omp.h> int main() { int data; #pragma omp parallel num_threads(3) { int id = omp_get_thread_num(); int total = omp_get_num_threads(); #pragma omp critical { // make sure only 1 thread exectutes the critical section at a time. data = id; // threads may interleaving the modification printf("Greetings from process %d out of %d with Data %d\n", id, total, data); } } printf("parallel for ends.\n"); return 0; }
注1:并行编程常会遇到资源竞争和协调的问题,于是就有各种策略来保证程序运行的可控性。
注2:在并行线程中对部分代码加锁(超市里n个人同时购物,但只有一个收银员,一次只能服务一人)
6. 进阶学习网站
标签:num,int,学习,omp,printf,OpenMP,data,id,摘录 来源: https://www.cnblogs.com/zbnbu/p/10987938.html