#include <Threading.h>

extern int		ShutdownControl;
extern int		ShutdownThreadCount;
extern int		ThreadCount;
extern int		ThreadRunLevel;
extern int		listenfd;
extern pthread_t	NetworkPID;

/*
   The thread manager provides two things, a way to see if the program
   is all started up (ie; all the threads are up and running), and a
   way for only exiting until all the other threads are done closing up.

   NOTE: The threadmanager itself doesn't count in the ThreadCount, because
   it is considered the master thread, and does nothing that needs to be
   warned before exiting, and even if it did, it is the only thing that can
   declair an exit, so that's not and issue :)
*/

void *Manager( void )
{
Error(0,"Threadedapp is starting up ...");
/* 
   Waits until all the other threads are up and running before doing things.
   Useful so you don't start losing data because a thread hadn't started up
*/
while ( ThreadCount < ThreadRunLevel )
	{
	usleep(EnforcedWait);
	}
ThreadCount--;	/* ticks away the config thread */
Error(0,"Done Starting Complete, App is running!");

/* 
   Basically wait to see if its time to shutdown ( signaled by setting ShutdownControl
   to a value of 1, then exit
*/
while ( 1 )
{
if ( ShutdownControl == 1 )
	{
	/* Good GOD!  Time to shutdown! */
	Error(3,"Shutdown request received, waiting for threads to shutdown ...");

        /* Wait until all the other threads report as closed */
	while( ThreadCount > 0 )
		  {
		  usleep(EnforcedWait);
		  /* Displays a wait to quit message, debuging only */
		  /*printf("Waiting ... %i more threads to close.\n",ThreadCount);*/
		  }
	/*printf("All Threads Except manager closed!  Now I die.\n");*/
	exit(0);
	}
usleep(EnforcedWait);
/* Sleep so the thread isn't constantly going and doing ifs (that's BAD!) */
}

}
