1 // RUN: %libomp-compile-and-run
2 #include <stdio.h>
3 #include "omp_testsuite.h"
4 
5 #define NUM_THREADS 10
6 
7 /*
8  After hot teams were enabled by default, the library started using levels
9  kept in the team structure.  The levels are broken in case foreign thread
10  exits and puts its team into the pool which is then re-used by another foreign
11  thread. The broken behavior observed is when printing the levels for each
12  new team, one gets 1, 2, 1, 2, 1, 2, etc.  This makes the library believe that
13  every other team is nested which is incorrect.  What is wanted is for the
14  levels to be 1, 1, 1, etc.
15 */
16 
17 int a = 0;
18 int level;
19 
20 typedef struct thread_arg_t {
21   int iterations;
22 } thread_arg_t;
23 
thread_function(void * arg)24 void* thread_function(void* arg) {
25   int i;
26   thread_arg_t* targ = (thread_arg_t*)arg;
27   int iterations = targ->iterations;
28   #pragma omp parallel private(i)
29   {
30     // level should always be 1
31     #pragma omp single
32     level = omp_get_level();
33 
34     #pragma omp for
35     for(i = 0; i < iterations; i++) {
36       #pragma omp atomic
37       a++;
38     }
39   }
40 }
41 
test_omp_team_reuse()42 int test_omp_team_reuse()
43 {
44   int i;
45   int success = 1;
46   pthread_t thread[NUM_THREADS];
47   thread_arg_t thread_arg[NUM_THREADS];
48   // launch NUM_THREADS threads, one at a time to perform thread_function()
49   for(i = 0; i < NUM_THREADS; i++) {
50     thread_arg[i].iterations = i + 1;
51     pthread_create(thread+i, NULL, thread_function, thread_arg+i);
52     pthread_join(*(thread+i), NULL);
53     // level read in thread_function()'s parallel region should be 1
54     if(level != 1) {
55       fprintf(stderr, "error: for pthread %d level should be 1 but "
56                       "instead equals %d\n", i, level);
57       success = 0;
58     }
59   }
60   // make sure the for loop works
61   int known_sum = (NUM_THREADS * (NUM_THREADS+1)) / 2;
62   if(a != known_sum) {
63     fprintf(stderr, "a should be %d but instead equals %d\n", known_sum, a);
64     success = 0;
65   }
66   return success;
67 }
68 
main()69 int main()
70 {
71   int i;
72   int num_failed=0;
73 
74   for(i = 0; i < REPETITIONS; i++) {
75     a = 0;
76     if(!test_omp_team_reuse()) {
77       num_failed++;
78     }
79   }
80   return num_failed;
81 }
82