0
我讀這個OpenMP tutorial,並遇到下面的程序:是否需要在OpenMP中將循環索引設置爲私有變量?
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define N 100
int main (int argc, char *argv[]) {
int nthreads, tid, i;
float a[N], b[N], c[N];
/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i;
#pragma omp parallel shared(a,b,c,nthreads) private(i,tid)
{
tid = omp_get_thread_num();
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
printf("Thread %d starting...\n",tid);
#pragma omp for
for (i=0; i<N; i++)
{
c[i] = a[i] + b[i];
printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);
}
} /* end of parallel section */
}
我有點糊塗了循環索引i
是否必須是private
變量或沒有。由於來自同一教程:
所有線程都可以修改和訪問所有變量(除循環索引)
如此看來線程無法控制i
,是不是?順便說一句,我試圖從private
變量刪除i
,結果似乎確定。