export set OMP_NUM_THREADS=3
编译:gcc -std=c99 -fopenmp openmp-test.c -Dsche
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char* argv[])
{
setenv("OMP_NUM_THREADS", "10", 0);
int nt = omp_get_num_threads();
printf("threads %d\n", nt);
#ifdef normal
#pragma omp parallel for
for(int i = 0; i < 10; ++i)
{
int id = omp_get_thread_num();
printf( "hello world %d, id %d\n", i, id);
}
return 0;
#endif
#ifdef pri
int x = 100;
#pragma omp parallel for firstprivate(x)
for(int i = 0; i < 10; ++i)
{
x+=i;
printf("x = %d\n", x);
}
printf("last x = %d\n", x);
return 0;
#endif
#ifdef lastpri
int x = 100;
#pragma omp parallel for firstprivate(x) lastprivate(x)
for(int i = 0; i < 10; ++i)
{
x+=i;
printf("x = %d\n", x);
}
printf("last x = %d\n", x);
return 0;
#endif
#ifdef critical
int x = 100;
int sum = 0;
#pragma omp parallel for shared(sum)
for(int i = 0; i < 5; ++i)
{
#pragma omp critical
sum += i*i;
}
printf("sum = %d\n", sum);
return 0;
#endif
#ifdef critical
int x = 100;
int sum = 0;
#pragma omp parallel for shared(sum)
for(int i = 0; i < 5; ++i)
{
#pragma omp critical
sum += i*i;
}
printf("sum = %d\n", sum);
return 0;
#endif
#ifdef reduct
int x = 100;
int sum = 0;
#pragma omp parallel for reduction(+:sum)
for(int i = 0; i < 5; ++i)
{
sum += i*i;
}
printf("sum = %d\n", sum);
sum = 1;
#pragma omp parallel for reduction(*:sum)
for(int i = 1; i < 5; ++i)
{
sum += i*i;
printf("temp sum = %d\n", sum);
}
printf("sum = %d\n", sum);
return 0;
#endif
#ifdef sche
int sum = 0;
#pragma omp parallel for schedule(static, 4)
for(int i = 0; i < 30; ++i)
{
sum += i*i;
int id = omp_get_thread_num();
printf( "i = %d, id = %d\n", i, id);
}
printf("sum = %d\n", sum);
return 0;
#endif
}