OpenMP是共享内存的编程环境。在实际并行编程中需要将数据进行共享化或者私有化。
OpenMP提供了一系列的子句来对共享和私有进行控制,常见的子句 :
private :
用于将一个或多个变量声明成线程私有变量,每个线程都有自己的私有变量副本,其他线程无法访问,即使在并行区域外有同名的共享变量,共享变量在并行区域内也不起作用,当然,并行区域内的私有变量在区域外也不起作用。
#include <stdio.h>#include <omp.h>#include <stdlib.h>main (int argc, char **argv) { int i ; int k=100 ; //定义共享变量 printf ("first k = %d, addr=%x\n", k, &i); omp_set_num_threads (4); #pragma omp parallel for private(k) //将k变成私有变量 for (i = 0; i <= 10; i++) { //在并行区域内,k作为私有变量 k = k+1 ; printf ("I am thread %d,i = %d,k=%d, addr =%x\n", omp_get_thread_num (), i,k,&k); } printf ("last k = %d, addr=%x\n", k, &k); }
first k = 100, addr=debd1e28 I am thread 0,i = 0,k=1, addr =debd1ddc I am thread 3,i = 9,k=32558, addr =59db9dec I am thread 3,i = 10,k=32559, addr =59db9dec I am thread 1,i = 3,k=32558, addr =5b1bbdec I am thread 1,i = 4,k=32559, addr =5b1bbdec I am thread 1,i = 5,k=32560, addr =5b1bbdec I am thread 2,i = 6,k=32558, addr =5a7badec I am thread 2,i = 7,k=32559, addr =5a7badec I am thread 2,i =&nb