00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #ifndef _SCHEDULER_H
00034 #define _SCHEDULER_H
00035
00036 #include <sys/types.h>
00037 #include <pthread.h>
00038 #include <unistd.h>
00039 #include <stdint.h>
00040 #include "mmultimap.h"
00041 #include "ThreadCreate.h"
00042 #include "NumberGen.h"
00043 #include "LockedSignal.h"
00044
00050 #include "TimerHandler.h"
00051
00064 class Scheduler : public RunThreadClass {
00065
00066 friend void _runNewThread(pthread_t* t, func f, void* arg,
00067 pthread_attr_t* attr, const char* fname, bool joinThread);
00068 friend void _runNewThreadClass(pthread_t* t, RunThreadClass* c, classfunc f,
00069 void* arg, pthread_attr_t* attr,
00070 const char* fname, bool joinThread);
00071 friend void* threadStart(void* vfa);
00072 friend class TimerHandler;
00073
00074 public:
00075 virtual ~Scheduler();
00076 static void haltScheduler();
00077
00078 static const uint64_t CLOCK_RESOLUTION = 1000;
00079 static bool simulated() { return Scheduler::Instance().isSimulated(); }
00080
00081 protected:
00082 typedef mace::map<uint64_t, pthread_t, mace::SoftState> IdThreadMap;
00083 virtual void runSchedulerThread();
00084 void fireTimer(bool locked);
00085 void joinThread(uint64_t vtid, pthread_t tid);
00086 void shutdownJoinThread(uint64_t vtid, pthread_t tid);
00087 size_t joinThreads(IdThreadMap& s);
00088 void lock() { assert(pthread_mutex_lock(&slock) == 0); }
00089 void unlock() { assert(pthread_mutex_unlock(&slock) == 0); }
00090
00091 virtual uint64_t schedule(TimerHandler& timer, uint64_t time, bool abs = false);
00092 virtual void cancel(TimerHandler& timer);
00093 virtual bool isSimulated() { return false; }
00094
00095 static void* startSchedulerThread(void* arg);
00096
00097 static Scheduler& Instance() {
00098 if (scheduler == 0) {
00099 scheduler = new Scheduler();
00100 _runNewThread(&scheduler->schedulerThread,
00101 Scheduler::startSchedulerThread, scheduler, 0,
00102 "Scheduler::startSchedulerThread", false);
00103 }
00104 return *scheduler;
00105 }
00106
00107
00108
00109 protected:
00110 bool running;
00111 uint64_t next;
00112
00113 LockedSignal sig;
00114
00115 typedef mace::multimap<uint64_t, TimerHandler*, mace::SoftState> TimerMap;
00116 TimerMap timers;
00117
00118 IdThreadMap joinSet;
00119 IdThreadMap shutdownJoinSet;
00120
00121 pthread_mutex_t slock;
00122
00123 static Scheduler* scheduler;
00124 Scheduler();
00125
00126 private:
00127 pthread_t schedulerThread;
00128 };
00129
00130 #endif // _SCHEDULER_H