00001 #include <time.h> 00002 #include "engine/loop_thread_obj.h" 00003 00004 FastLoopThreadObj::FastLoopThreadObj(const std::string n) : ThreadObj(n) 00005 { 00006 } 00007 00008 FastLoopThreadObj::~FastLoopThreadObj() 00009 { 00010 } 00011 00012 void FastLoopThreadObj::Main() 00013 { 00014 while(!GetAskStop()) 00015 Loop(); 00016 } 00017 00018 // in microseconds 00019 const unsigned int sleep_time_min = 1000; 00020 const unsigned int sleep_time_max = 100000; 00021 00022 // in seconds 00023 const /*unsigned*/ int awake_time = 10; // time before beginning to sleep 00024 const /*unsigned*/ int fall_asleep_time = 20; // time tobe totally asleep 00025 00026 LoopThreadObj::LoopThreadObj(const std::string n) : FastLoopThreadObj(n), sleep_mutex(NORMAL_MUTEX) 00027 { 00028 //printf("Starting %p : %s", this, n.c_str()); 00029 sleep_time = sleep_time_min; 00030 time(&last_wake); 00031 } 00032 00033 LoopThreadObj::~LoopThreadObj() 00034 { 00035 // This would trigger a race condition as 00036 // the destructor of subclasses has already been 00037 // called. 00038 // Make sure sleep_mutex has been released 00039 //SetAskStop(true); 00040 //while(!GetStopped()) 00041 // usleep(50000); 00042 } 00043 00044 void LoopThreadObj::WakeUp() 00045 { 00046 MUTEX_LOCK(sleep_mutex); 00047 sleep_time = sleep_time_min; 00048 time(&last_wake); 00049 MUTEX_UNLOCK(sleep_mutex); 00050 } 00051 00052 void LoopThreadObj::Main() 00053 { 00054 while(!GetAskStop()) 00055 { 00056 //usleep(50000); // Sleep 0.05 sec 00057 00058 // Increase sleep time if necessary: 00059 MUTEX_LOCK(sleep_mutex); 00060 usleep(sleep_time); // Sleep 0.005 sec 00061 00062 time_t now; 00063 time(&now); 00064 if( last_wake + awake_time < /*(unsigned int)*/ now 00065 && last_wake + awake_time + fall_asleep_time > /*(unsigned int)*/now ) 00066 sleep_time = sleep_time_min + (sleep_time_max - sleep_time_min) * (now - last_wake - awake_time) / fall_asleep_time; 00067 else 00068 sleep_time = sleep_time_max; 00069 00070 MUTEX_UNLOCK(sleep_mutex); 00071 00072 Loop(); 00073 } 00074 } 00075 00076 unsigned int LoopThreadObj::GetSleepTime() 00077 { 00078 unsigned int tmp; 00079 MUTEX_LOCK(sleep_mutex); 00080 tmp = sleep_time; 00081 MUTEX_UNLOCK(sleep_mutex); 00082 return tmp; 00083 } 00084
1.5.8