3 * @purpose Implementation of thread control
9 pthread_mutex_t mutex_runstate = PTHREAD_MUTEX_INITIALIZER;
10 Runstate runstate = RUNNING;
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
17 void Thread_QuitProgram(bool error)
19 if (runstate != RUNNING)
21 Log(LOGNOTE, "Called when program is not running; runstate = %d", runstate);
26 Log(LOGNOTE, "Program will quit; error = %d", (int)error);
28 //CRITICAL SECTION - We do NOT want multiple threads editing the runstate at the same time!
29 pthread_mutex_lock(&mutex_runstate);
31 runstate = QUIT_ERROR;
35 gettimeofday(&g_options.end_time, NULL);
36 pthread_mutex_unlock(&mutex_runstate);
37 // End critical section
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.
44 Runstate Thread_Runstate()
46 //TODO: Add real exit conditions; for testing purposes, set a timeout
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)
53 Thread_QuitProgram(false);
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.