Parallel Programming - Commit before I break things
[matches/honours.git] / course / semester2 / pprog / assignment1 / openmp / nbody.c
index 6eb9ed4..c487201 100644 (file)
@@ -8,6 +8,9 @@
 #include "../single-thread/nbody.c" // Include original code
 #include "graphics.h" // For Graphics_Run function only
 
+omp_lock_t graphics_lock;
+bool graphics_busy = false;
+
 /**
  * @function Simulation_Run
  * @purpose Start the simulation
@@ -32,7 +35,7 @@ void Simulation_Run(int argc, char ** argv)
                omp_set_num_threads(1);
 
 
-               
+       omp_init_lock(&graphics_lock);
 
        #pragma omp parallel sections
        {
@@ -50,9 +53,7 @@ void Simulation_Run(int argc, char ** argv)
                                        break;
                                }                               
 
-
-                               if (options.draw_graphics == false && options.verbosity != 0 
-                                       && universe.steps % options.verbosity == 1)
+                               if (options.verbosity != 0 && universe.steps % options.verbosity == 1)
                                {
                                        DisplayStatistics();
                                }
@@ -71,6 +72,8 @@ void Simulation_Run(int argc, char ** argv)
                }
 
        }
+
+       omp_destroy_lock(&graphics_lock);
 }
 
 /**
@@ -93,6 +96,13 @@ void Compute(void)
                System_Forces(&s, &universe);
        }
 
+       // Wait for graphics to finish drawing
+
+       if (options.draw_graphics && options.pedantic_graphics)
+       {
+               while (graphics_busy);
+       }       
+
        #pragma omp parallel for
        for (unsigned i = 0; i < options.num_threads; ++i)
        {
@@ -105,4 +115,39 @@ void Compute(void)
 
        universe.steps += 1;
 
+       // Tell graphics to continue
+       if (options.draw_graphics && options.pedantic_graphics)
+       {
+               omp_set_lock(&graphics_lock);
+               graphics_busy = true;
+               omp_unset_lock(&graphics_lock);
+               
+       }
+
+}
+
+/**
+ * @function BeforeDraw
+ * @purpose Called before the graphics thread draws bodies. 
+ *     If pedantic graphics are used, will wait until graphics_busy is set to true before drawing
+ */
+void BeforeDraw()
+{
+       if (!options.pedantic_graphics)
+               return;
+       while (graphics_busy == false);
+}
+
+/**
+ * @function AfterDraw
+ * @purpose Called after the graphics thread draws bodies
+ *     If pedantic graphics used, will unset graphics_busy when done drawing
+ */
+void AfterDraw()
+{
+       if (!options.pedantic_graphics)
+               return;
+       omp_set_lock(&graphics_lock);
+       graphics_busy = false;
+       omp_unset_lock(&graphics_lock);
 }

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