/* A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. This exercise help you understand the order of execution. How to Compile: $ cc race_condition.c -o race_condition How to Setup Runtime Environment: $ export OMP_NUM_THREADS=4 How to Run Program: $ aprun -n 1 -d 4 ./race_condition Output: There is something wrong with this example fix it Thread 2 : My value of tid (thread id) is 2 Thread 3 : My value of tid (thread id) is 3 Thread 1 : My value of tid (thread id) is 1 Thread 0 : My value of tid (thread id) is 0 Did you figure out what's wrong? Hint: do a # comparison So right now the thread_id is shared variables among all the threads. if you run the program multiple times. You will see */ // The following C libraries are needed. #include // Is needed for exiting early if an error occurs #include // Is needed for printing the final results #include // Is needed for parsing the user's command-line arguments #include // Is needed or OpenMP related stuff int main(int argc, char **argv) { int i, j; // loops index variables int thread_id; //Stores an integer value id of each thread printf("There is something wrong with this example fix it\n"); /* This exercise tries to illustrate a simple parallel OpenMP program. Run it several times. At some occasions the printed output is "wrong". Why is that? What happens when you add the the thread_id variable to the private list private(i,j,thread_id) run it again for multiple times and see the difference. The pragma stops the compiler during reading the file, and warns it of special event. Here it tells it that some OpenMP parallelism is happening. It also tells the compiler that make sure it make a copy of the variables i,j, and thread_id for each thread in the pool. Even if you do not explicitly make loop index variables private, the OpenMP supported compilers will do that. but If you dont make the thread_id private here, running the program multiple times will result in different values. */ #pragma omp parallel private(i, j) { for (i = 0; i < 1000; i++) for (j = 0; j < 1000; j++) thread_id = omp_get_thread_num(); printf("Thread %d : My value of tid (thread id) is %d\n", omp_get_thread_num(), thread_id); } printf("\n Did you figure out what's wrong? \n Hint: do a # comparison\n"); }