Parallel Programming - Final version
[matches/honours.git] / course / semester2 / pprog / assignment1 / openmp / nbody.c
index 053625b..bc2d173 100644 (file)
@@ -13,6 +13,8 @@
 System * sub_system = NULL; 
 #endif //OVER_ENGINEERED
 
+omp_lock_t runstate_lock;
+
 /**
  * @function Simulation_Run
  * @purpose Start the simulation
@@ -20,7 +22,7 @@ System * sub_system = NULL;
  */
 void Simulation_Run(int argc, char ** argv)
 {      
-       
+       omp_init_lock(&runstate_lock);
        if (options.num_threads == 0)
                options.num_threads = omp_get_max_threads();
 
@@ -38,15 +40,21 @@ void Simulation_Run(int argc, char ** argv)
                        }       
 
 
-                       #pragma omp parallel sections num_threads(2)
+                       #pragma omp parallel num_threads(2)
                        {
-                               #pragma omp section
-                               {
-                                       Compute();
-                               }
-                               #pragma omp section
+                               // This can't be done with sections!
+                               // Because glut is useless, and can only be dealt with in the main thread
+                               // I just hope that thread "0" is always the main thread!
+                               if (omp_get_thread_num() == 0) // #pragma omp section
                                {
+                                       //printf("Thread %d gets graphics\n", omp_get_thread_num());
                                        glutMainLoop();
+                                       QuitProgram(false); // Program gets to here if the window is quit
+                               } 
+                               else // #pragma omp section
+                               {
+                                       //printf("Thread %d gets computations\n", omp_get_thread_num());
+                                       Compute();
                                }
                        }
                        return;
@@ -55,7 +63,7 @@ void Simulation_Run(int argc, char ** argv)
        Compute();
 
 
-
+       omp_destroy_lock(&runstate_lock);
 }
 
 
@@ -134,5 +142,15 @@ void Compute(void)
                                
                }
        }
+       QuitProgram(false);
+}
+
+void QuitProgram(bool error)
+{
+       if (runstate == QUIT || runstate == QUIT_ERROR)
+               return;
+       omp_set_lock(&runstate_lock);
+       runstate = (error) ? QUIT_ERROR : QUIT;
+       omp_unset_lock(&runstate_lock);
 }
 

UCC git Repository :: git.ucc.asn.au