openmp
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenMP
OpenMP
Purpose
目的
Guide agents through OpenMP shared-memory parallelism: with scheduling clauses, reductions, data-sharing attributes, SIMD hints, task parallelism, OpenMP 5.x GPU offloading, common pitfalls (false sharing, data races), environment tuning, and profiling with Score-P or TAU.
#pragma omp parallel fortarget指导 Agent 进行 OpenMP 共享内存并行编程:带调度子句的 、reduction、数据共享属性、SIMD 提示、任务并行、OpenMP 5.x GPU 卸载、常见陷阱(false sharing、数据竞争)、环境调优,以及使用 Score-P 或 TAU 进行性能分析。
#pragma omp parallel fortargetWhen to Use
使用场景
- Parallelizing C/C++/Fortran loops on multicore CPUs
- Implementing reductions (sum, max, custom)
- Task parallelism for irregular workloads
- Offloading compute to GPU with OpenMP target directives
- Diagnosing scaling failures (false sharing, load imbalance)
- Tuning thread count and spin behavior
- 在多核 CPU 上并行化 C/C++/Fortran 循环
- 实现 reduction(求和、最大值、自定义)
- 针对不规则工作负载使用任务并行
- 使用 OpenMP target 指令将计算卸载到 GPU
- 诊断并行扩展性能问题(false sharing、负载不均衡)
- 调整线程数量和自旋行为
Workflow
工作流
1. Basic parallel for
1. 基础并行 for 循环
c
#include <omp.h>
#include <stdio.h>
int main(void) {
const int n = 1000000;
double sum = 0.0;
#pragma omp parallel for reduction(+:sum)
for (int i = 0; i < n; i++)
sum += i * 0.001;
printf("sum = %f, threads = %d\n", sum, omp_get_max_threads());
return 0;
}bash
gcc -fopenmp -O3 -o omp_sum omp_sum.c
export OMP_NUM_THREADS=8
./omp_sumc
#include <omp.h>
#include <stdio.h>
int main(void) {
const int n = 1000000;
double sum = 0.0;
#pragma omp parallel for reduction(+:sum)
for (int i = 0; i < n; i++)
sum += i * 0.001;
printf("sum = %f, threads = %d\n", sum, omp_get_max_threads());
return 0;
}bash
gcc -fopenmp -O3 -o omp_sum omp_sum.c
export OMP_NUM_THREADS=8
./omp_sum2. Schedule clauses
2. 调度子句
c
#pragma omp parallel for schedule(static) // equal chunks, low overhead
#pragma omp parallel for schedule(dynamic, 64) // dynamic chunks of 64
#pragma omp parallel for schedule(guided) // decreasing chunk size
#pragma omp parallel for schedule(auto) // compiler/runtime decides| Schedule | Best for |
|---|---|
| Uniform work per iteration |
| Variable iteration cost |
| Decreasing iteration cost |
| Cache blocking with interleaved chunks |
c
#pragma omp parallel for schedule(static) // equal chunks, low overhead
#pragma omp parallel for schedule(dynamic, 64) // dynamic chunks of 64
#pragma omp parallel for schedule(guided) // decreasing chunk size
#pragma omp parallel for schedule(auto) // compiler/runtime decides| Schedule | 适用场景 |
|---|---|
| 每次迭代的工作量均匀 |
| 每次迭代的成本可变 |
| 每次迭代的成本递减 |
| 使用交错式块进行缓存阻塞 |
3. Data sharing attributes
3. 数据共享属性
c
int shared_var = 0;
#pragma omp parallel private(i) shared(shared_var)
{
int i = omp_get_thread_num();
#pragma omp atomic
shared_var += i;
}
// firstprivate — copy in; lastprivate — copy out after loop
#pragma omp parallel for firstprivate(offset) lastprivate(result)
for (int i = 0; i < n; i++) { ... }| Clause | Meaning |
|---|---|
| Uninitialized per-thread copy |
| One variable, all threads |
| Combine at end (+, *, max, &&, ||) |
| Initialize from master |
| Master gets last iteration value |
c
int shared_var = 0;
#pragma omp parallel private(i) shared(shared_var)
{
int i = omp_get_thread_num();
#pragma omp atomic
shared_var += i;
}
// firstprivate — copy in; lastprivate — copy out after loop
#pragma omp parallel for firstprivate(offset) lastprivate(result)
for (int i = 0; i < n; i++) { ... }| 子句 | 含义 |
|---|---|
| 每线程一个未初始化的副本 |
| 一个变量,由所有线程共享 |
| 在结束时合并(+, *, max, &&, ||) |
| 从 master 初始化 |
| master 获取最后一次迭代的值 |
4. SIMD vectorization hint
4. SIMD 向量化提示
c
#pragma omp simd
for (int i = 0; i < n; i++)
c[i] = a[i] + b[i];
// SIMD + parallel
#pragma omp parallel for simd
for (int i = 0; i < n; i++)
c[i] = a[i] * b[i];Requires or with compiler SIMD support. Check with .
-fopenmp-simd-fopenmp-fopt-info-vecc
#pragma omp simd
for (int i = 0; i < n; i++)
c[i] = a[i] + b[i];
// SIMD + parallel
#pragma omp parallel for simd
for (int i = 0; i < n; i++)
c[i] = a[i] * b[i];需要使用 ,或使用支持 SIMD 的编译器并启用 。可通过 检查。
-fopenmp-simd-fopenmp-fopt-info-vec5. Task parallelism
5. 任务并行
c
#pragma omp parallel
{
#pragma omp single
{
for (int i = 0; i < 10; i++) {
#pragma omp task firstprivate(i)
process_subtree(i);
}
#pragma omp taskwait
}
}Tasks suit recursive algorithms (quicksort, tree traversal) where loop parallelism doesn't fit.
c
#pragma omp parallel
{
#pragma omp single
{
for (int i = 0; i < 10; i++) {
#pragma omp task firstprivate(i)
process_subtree(i);
}
#pragma omp taskwait
}
}Task 适合递归算法(quicksort、树遍历)等不适合使用循环并行的场景。
6. Timing
6. 计时
c
double start = omp_get_wtime();
#pragma omp parallel for
for (int i = 0; i < n; i++) work(i);
double elapsed = omp_get_wtime() - start;
printf("elapsed: %f s\n", elapsed);c
double start = omp_get_wtime();
#pragma omp parallel for
for (int i = 0; i < n; i++) work(i);
double elapsed = omp_get_wtime() - start;
printf("elapsed: %f s\n", elapsed);7. GPU target offloading (OpenMP 5.x)
7. GPU target 卸载(OpenMP 5.x)
c
#pragma omp target teams distribute parallel for map(to:a[0:n]) map(from:c[0:n])
for (int i = 0; i < n; i++)
c[i] = a[i] * 2.0f;bash
undefinedc
#pragma omp target teams distribute parallel for map(to:a[0:n]) map(from:c[0:n])
for (int i = 0; i < n; i++)
c[i] = a[i] * 2.0f;bash
undefinedNVIDIA offload
NVIDIA offload
gcc -fopenmp -foffload=-march=sm_80 -o offload offload.c
gcc -fopenmp -foffload=-march=sm_80 -o offload offload.c
Check device
Check device
export OMP_DEFAULT_TARGET_DEVICE=1
Requires compiler offload support (GCC offload, Clang/OpenMP, NVIDIA HPC SDK).export OMP_DEFAULT_TARGET_DEVICE=1
需要编译器支持 offload(GCC offload、Clang/OpenMP、NVIDIA HPC SDK)。8. Environment variables
8. 环境变量
bash
export OMP_NUM_THREADS=16
export OMP_PROC_BIND=close # bind threads to nearby cores
export OMP_PLACES=cores
export GOMP_SPINCOUNT=2000 # spin before sleep
export OMP_WAIT_POLICY=active # active vs passive waiting
export OMP_DISPLAY_ENV=true # print config at startupbash
export OMP_NUM_THREADS=16
export OMP_PROC_BIND=close # bind threads to nearby cores
export OMP_PLACES=cores
export GOMP_SPINCOUNT=2000 # spin before sleep
export OMP_WAIT_POLICY=active # active vs passive waiting
export OMP_DISPLAY_ENV=true # print config at startup9. Profiling
9. 性能分析
bash
undefinedbash
undefinedScore-P (compile with wrapper)
Score-P (compile with wrapper)
scorep gcc -fopenmp -o app app.c
export SCOREP_METRIC_MANAGER=1
scorep ./app
scorep-score -f scorep_*/profile.cubex
scorep gcc -fopenmp -o app app.c
export SCOREP_METRIC_MANAGER=1
scorep ./app
scorep-score -f scorep_*/profile.cubex
TAU
TAU
tau_cc.sh -fopenmp -o app app.c
export TAU_TRACE=1
./app
pprof app profile.*
undefinedtau_cc.sh -fopenmp -o app app.c
export TAU_TRACE=1
./app
pprof app profile.*
undefined10. Pitfalls
10. 常见陷阱
False sharing: threads modify adjacent cache lines.
c
// Bad: sum_array[tid] on same cache line
#pragma omp parallel
{
int tid = omp_get_thread_num();
sum_array[tid] += local_sum; // pad to 64 bytes between elements
}
// Fix: padding
double sum_padded[MAX_THREADS][8]; // 8 doubles = 64 bytesNested parallelism:
bash
export OMP_MAX_ACTIVE_LEVELS=2
export OMP_NESTED=true # deprecated; use MAX_ACTIVE_LEVELSFalse sharing:线程修改相邻的缓存行。
c
// Bad: sum_array[tid] on same cache line
#pragma omp parallel
{
int tid = omp_get_thread_num();
sum_array[tid] += local_sum; // pad to 64 bytes between elements
}
// Fix: padding
double sum_padded[MAX_THREADS][8]; // 8 doubles = 64 bytesNested parallelism:
bash
export OMP_MAX_ACTIVE_LEVELS=2
export OMP_NESTED=true # deprecated; use MAX_ACTIVE_LEVELSCommon Problems
常见问题
| Symptom | Cause | Fix |
|---|---|---|
| No speedup | Loop too small | Increase work; check |
| Wrong reduction result | Race on non-reduction var | Use |
| Slower with more threads | False sharing | Pad per-thread arrays |
| GPU offload fails | No target device | Check |
| Threads not bound | Default spread | |
| Nested deadlock | Oversubscription | Limit |
| 症状 | 原因 | 修复方式 |
|---|---|---|
| 没有加速 | 循环过小 | 增大工作量;检查 |
| reduction 结果错误 | 非 reduction 变量存在竞争 | 使用 |
| 线程越多反而越慢 | False sharing | 为每线程数组添加填充 |
| GPU offload 失败 | 没有 target 设备 | 检查 |
| 线程未绑定 | 默认分散策略 | |
| 嵌套死锁 | 过度订阅 | 限制每一层的 |
Related Skills
相关 Skill
- — distributed memory complement
skills/hpc/mpi - — false sharing deep dive
skills/low-level-programming/cpu-cache-opt - — GPU programming alternative to target offload
skills/gpu/cuda - — OpenMP region analysis in VTune
skills/profilers/intel-vtune-amd-uprof - —
skills/compilers/gccflags-fopenmp - — NUMA-aware thread binding
skills/allocators/numa-programming
- — 分布式内存的补充方案
skills/hpc/mpi - — false sharing 深入解析
skills/low-level-programming/cpu-cache-opt - — target 卸载之外的 GPU 编程替代方案
skills/gpu/cuda - — 在 VTune 中进行 OpenMP region 分析
skills/profilers/intel-vtune-amd-uprof - —
skills/compilers/gcc编译选项-fopenmp - — NUMA 感知的线程绑定
skills/allocators/numa-programming