voidtest_numthread() { printf("max thread nums is %d\n", omp_get_max_threads()); printf("omp_get_num_threads: out parallel region is %d\n", omp_get_num_threads()); omp_set_num_threads(2); printf("after omp_set_num_threads: max thread nums is %d\n", omp_get_max_threads()); #pragma omp parallel { #pragma omp master { printf("omp_get_num_threads: in parallel region is %d\n\n", omp_get_num_threads()); } printf("1: thread %d is running\n", omp_get_thread_num()); } printf("\n"); #pragma omp parallel num_threads(3) { printf("2: thread %d is running\n", omp_get_thread_num()); } }
下面是程序运行结果:
1 2 3 4 5 6 7 8 9 10 11
max thread nums is 4 omp_get_num_threads: out parallel region is 1 after omp_set_num_threads: max thread nums is 2 omp_get_num_threads: in parallel region is 2
1: thread 0 is running 1: thread 1 is running
2: thread 0 is running 2: thread 1 is running 2: thread 2 is running
voidtest_nested() { int tid; printf("nested state is %d\n", omp_get_nested());
#pragma omp parallel num_threads(2) private(tid) { tid = omp_get_thread_num(); printf("In outer parallel region: thread %d is running\n", tid); #pragma omp parallel num_threads(2) firstprivate(tid) { printf("In nested parallel region: thread %d is running and outer thread is %d\n", omp_get_thread_num(), tid); } }
omp_set_nested(1); printf("\n"); printf("nested state is %d\n", omp_get_nested());
#pragma omp parallel num_threads(2) private(tid) { tid = omp_get_thread_num(); printf("In outer parallel region: thread %d is running\n", tid); #pragma omp parallel num_threads(2) { printf("In nested parallel region: thread %d is running and outer thread is %d\n", omp_get_thread_num(), tid); } } }
下面是程序运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 13
nested state is 0 In outer parallel region: thread 0 is running In nested parallel region: thread 0 is running and outer thread is 0 In outer parallel region: thread 1 is running In nested parallel region: thread 0 is running and outer thread is 1
nested state is 1 In outer parallel region: thread 1 is running In outer parallel region: thread 0 is running In nested parallel region: thread 0 is running and outer thread is 0 In nested parallel region: thread 0 is running and outer thread is 1 In nested parallel region: thread 1 is running and outer thread is 1 In nested parallel region: thread 1 is running and outer thread is 0