2d6b228b422e0018b9f05662f707c75bdd95e0ad
[matches/honours.git] / course / semester2 / pprog / assignment1 / mthread / main.c
1
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <pthread.h>
5
6 #include "nbody.h"
7 #include "graphics.h"
8
9 unsigned numberOfProcessors;
10
11 System universe;
12 pthread_t compute_thread;
13 pthread_mutex_t mutex_terminate;
14 bool terminate = false;
15
16 void Cleanup_Threads(void); //Cleanup for threads
17
18 // This is main function. Do not change it.
19 int main(int argc, char** argv)
20 {
21         if (argc < 2) 
22         {
23                 printf("Please provide the filename, i.e. \'%s bodiesfield.dat\'\n", argv[0]);
24                 exit(EXIT_FAILURE);
25         }
26         if (argc == 2)
27         {
28                 System_Init(&universe,argv[1]);
29                 atexit(Universe_Cleanup);
30         }
31         if (argc == 3) 
32         {
33                 numberOfProcessors = atoi(argv[2]);
34         }
35         
36         atexit(Cleanup_Threads);
37         
38         // Create a thread to handle computation loop
39         
40         if (pthread_create(&compute_thread, NULL, Compute_Thread, (void*)&universe) != 0)
41         {
42                 perror("Error creating compute thread");
43                 exit(EXIT_FAILURE);
44         }
45         
46         Graphics_Run(argc, argv); // Run graphics loop in the main thread
47         
48         
49 }
50
51 /**
52  * Function will be called when exit() is called.
53  * Will set condition for child threads to terminate, and then join with them.
54  * The main thread is responsible for calling exit().
55  */ 
56 void Cleanup_Threads()
57 {
58         printf("Set terminate\n");
59         pthread_mutex_lock(&mutex_terminate);
60         terminate = true;
61         pthread_mutex_unlock(&mutex_terminate);
62         pthread_join(compute_thread, NULL);
63         pthread_exit(NULL);
64 }

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