OpenMP 中数组约简
问题:
如何针对数组在 OpenMP 中执行约简运算?
回答:
OpenMP 的确支持数组约简。有两种方法可以实现:
方法 1:使用“私有”变量
为每个线程创建 S 的私有副本,并行填充它们,然后在临界区中将它们合并到 S 中:
int A[] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S[10] = {0}; #pragma omp parallel { int S_private[10] = {0}; #pragma omp for for (int n = 0; n < 10; ++n) { for (int m = 0; m <= n; ++m) { S_private[n] += A[m]; } } #pragma omp critical { for (int n = 0; n < 10; ++n) { S[n] += S_private[n]; } } }
方法 2:使用多维数组
创建一个维度为 10*nthreads 的数组,并行填充它,然后在没有临界区的情况下将其合并到 S 中:
int A[] = {84, 30, 95, 94, 36, 73, 52, 23, 2, 13}; int S[10] = {0}; int *S_private; #pragma omp parallel { const int nthreads = omp_get_num_threads(); const int ithread = omp_get_thread_num(); #pragma omp single { S_private = new int[10 * nthreads]; for (int i = 0; i < (10 * nthreads); i++) S_private[i] = 0; } #pragma omp for for (int n = 0; n < 10; ++n) { for (int m = 0; m <= n; ++m) { S_private[ithread * 10 + n] += A[m]; } } #pragma omp for for (int i = 0; i < 10; i++) { for (int t = 0; t < nthreads; t++) { S[i] += S_private[10 * t + i]; } } } delete[] S_private;
以上是如何在 OpenMP 中执行数组缩减?的详细内容。更多信息请关注PHP中文网其他相关文章!