Get threads to deal with exit conditions, create timestamps
[matches/MCTX3420.git] / server / thread.c
1 /**
2  * @file thread.c
3  * @purpose Implementation of thread control
4  */
5
6 #include "thread.h"
7 #include "options.h"
8
9 pthread_mutex_t mutex_runstate = PTHREAD_MUTEX_INITIALIZER;
10 Runstate runstate = RUNNING;
11
12 /**
13  * Set the runstate, causing all threads to exit when they next check Thread_Runstate
14  * Repeated calls to this function have no effect on the runstate.
15  * @param error - Set to true to indicate an error occured
16  */
17 void Thread_QuitProgram(bool error)
18 {
19         if (runstate != RUNNING)
20         {
21                 Log(LOGNOTE, "Called when program is not running; runstate = %d", runstate);
22                 return;
23         }
24
25
26         Log(LOGNOTE, "Program will quit; error = %d", (int)error);
27
28         //CRITICAL SECTION - We do NOT want multiple threads editing the runstate at the same time!
29         pthread_mutex_lock(&mutex_runstate);
30         if (error)
31                 runstate = QUIT_ERROR;
32         else
33                 runstate = QUIT;
34         
35         gettimeofday(&g_options.end_time, NULL);
36         pthread_mutex_unlock(&mutex_runstate);
37         // End critical section
38 }
39
40 /**
41  * Check the runstate; to be called periodically by all threads.
42  * This function will call Thread_QuitProgram and change the Runstate there is an exit condition detected.
43  */
44 Runstate Thread_Runstate()
45 {
46         //TODO: Add real exit conditions; for testing purposes, set a timeout
47         /*
48         struct timeval time;
49         gettimeofday(&time, NULL);
50         Log(LOGDEBUG, "It has been %d seconds since program started.", time.tv_sec - g_options.start_time.tv_sec);
51         if (time.tv_sec - g_options.start_time.tv_sec > 3)
52         {
53                 Thread_QuitProgram(false);
54         }
55         */
56         
57         // Just reading the runstate doesn't really require a mutex
58         // The worst case: Another thread alters the runstate before this thread gets the result; this thread thinks the program is still running
59         // In that case, the thread will run an extra cycle of its loop and *then* exit. Since the runstate can only be changed once.
60         // We could put a mutex here anyway, but it will have an impact on how fast the loops can run.
61         return runstate;
62 }

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