OpenMP是共享內(nèi)存的編程環(huán)境。在實(shí)際并行編程中需要將數(shù)據(jù)進(jìn)行共享化或者私有化。
OpenMP提供了一系列的子句來(lái)對(duì)共享和私有進(jìn)行控制,常見(jiàn)的子句 :
private :
用于將一個(gè)或多個(gè)變量聲明成線程私有變量,每個(gè)線程都有自己的私有變量副本,其他線程無(wú)法訪問(wèn),即使在并行區(qū)域外有同名的共享變量,共享變量在并行區(qū)域內(nèi)也不起作用,當(dāng)然,并行區(qū)域內(nèi)的私有變量在區(qū)域外也不起作用。
#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++) { //在并行區(qū)域內(nè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