1
0

Migrated cSleep and cTimer to std::chrono

This commit is contained in:
Tiger Wang 2014-10-20 18:59:40 +01:00
parent aa19a3afb0
commit bde99d684e
18 changed files with 45 additions and 168 deletions

@ -112,7 +112,6 @@ SET (HDRS
MapManager.h MapManager.h
Matrix4.h Matrix4.h
MemoryLeak.h MemoryLeak.h
MersenneTwister.h
MobCensus.h MobCensus.h
MobFamilyCollecter.h MobFamilyCollecter.h
MobProximityCounter.h MobProximityCounter.h

@ -16,7 +16,6 @@
#include "Mobs/Monster.h" #include "Mobs/Monster.h"
#include "ChatColor.h" #include "ChatColor.h"
#include "OSSupport/Socket.h" #include "OSSupport/Socket.h"
#include "OSSupport/Timer.h"
#include "Items/ItemHandler.h" #include "Items/ItemHandler.h"
#include "Blocks/BlockHandler.h" #include "Blocks/BlockHandler.h"
#include "Blocks/BlockSlab.h" #include "Blocks/BlockSlab.h"
@ -63,8 +62,6 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) :
m_TimeSinceLastPacket(0), m_TimeSinceLastPacket(0),
m_Ping(1000), m_Ping(1000),
m_PingID(1), m_PingID(1),
m_PingStartTime(0),
m_LastPingTime(1000),
m_BlockDigAnimStage(-1), m_BlockDigAnimStage(-1),
m_BlockDigAnimSpeed(0), m_BlockDigAnimSpeed(0),
m_BlockDigAnimX(0), m_BlockDigAnimX(0),
@ -87,9 +84,7 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) :
s_ClientCount++; // Not protected by CS because clients are always constructed from the same thread s_ClientCount++; // Not protected by CS because clients are always constructed from the same thread
m_UniqueID = s_ClientCount; m_UniqueID = s_ClientCount;
m_LastPingTime = std::chrono::steady_clock::now();
cTimer t1;
m_LastPingTime = t1.GetNowTime();
LOGD("New ClientHandle created at %p", this); LOGD("New ClientHandle created at %p", this);
} }
@ -383,8 +378,7 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID,
// Delay the first ping until the client "settles down" // Delay the first ping until the client "settles down"
// This should fix #889, "BadCast exception, cannot convert bit to fm" error in client // This should fix #889, "BadCast exception, cannot convert bit to fm" error in client
cTimer t1; m_LastPingTime = std::chrono::steady_clock::now() + std::chrono::seconds(3); // Send the first KeepAlive packet in 3 seconds
m_LastPingTime = t1.GetNowTime() + 3000; // Send the first KeepAlive packet in 3 seconds
cRoot::Get()->GetPluginManager()->CallHookPlayerSpawned(*m_Player); cRoot::Get()->GetPluginManager()->CallHookPlayerSpawned(*m_Player);
} }
@ -1694,8 +1688,7 @@ void cClientHandle::HandleKeepAlive(int a_KeepAliveID)
{ {
if (a_KeepAliveID == m_PingID) if (a_KeepAliveID == m_PingID)
{ {
cTimer t1; m_Ping = std::chrono::steady_clock::now() - m_PingStartTime;
m_Ping = (short)((t1.GetNowTime() - m_PingStartTime) / 2);
} }
} }
@ -1919,11 +1912,10 @@ void cClientHandle::Tick(float a_Dt)
// Send a ping packet: // Send a ping packet:
if (m_State == csPlaying) if (m_State == csPlaying)
{ {
cTimer t1; if ((m_LastPingTime + cClientHandle::PING_TIME_MS <= std::chrono::steady_clock::now()))
if ((m_LastPingTime + cClientHandle::PING_TIME_MS <= t1.GetNowTime()))
{ {
m_PingID++; m_PingID++;
m_PingStartTime = t1.GetNowTime(); m_PingStartTime = std::chrono::steady_clock::now();
m_Protocol->SendKeepAlive(m_PingID); m_Protocol->SendKeepAlive(m_PingID);
m_LastPingTime = m_PingStartTime; m_LastPingTime = m_PingStartTime;
} }

@ -210,7 +210,7 @@ public:
const AString & GetUsername(void) const; const AString & GetUsername(void) const;
void SetUsername( const AString & a_Username); void SetUsername( const AString & a_Username);
inline short GetPing(void) const { return m_Ping; } inline short GetPing(void) const { return static_cast<short>(std::chrono::duration_cast<std::chrono::milliseconds>(m_Ping).count()); }
void SetViewDistance(int a_ViewDistance); void SetViewDistance(int a_ViewDistance);
int GetViewDistance(void) const { return m_ViewDistance; } int GetViewDistance(void) const { return m_ViewDistance; }
@ -367,11 +367,11 @@ private:
/** Seconds since the last packet data was received (updated in Tick(), reset in DataReceived()) */ /** Seconds since the last packet data was received (updated in Tick(), reset in DataReceived()) */
float m_TimeSinceLastPacket; float m_TimeSinceLastPacket;
short m_Ping; std::chrono::steady_clock::duration m_Ping;
int m_PingID; int m_PingID;
long long m_PingStartTime; std::chrono::steady_clock::time_point m_PingStartTime;
long long m_LastPingTime; std::chrono::steady_clock::time_point m_LastPingTime;
static const unsigned short PING_TIME_MS = 1000; // Vanilla sends 1 per 20 ticks (1 second or every 1000 ms) std::chrono::milliseconds PING_TIME_MS = std::chrono::milliseconds(1000); // Vanilla sends 1 per 20 ticks (1 second or every 1000 ms)
// Values required for block dig animation // Values required for block dig animation
int m_BlockDigAnimStage; // Current stage of the animation; -1 if not digging int m_BlockDigAnimStage; // Current stage of the animation; -1 if not digging

@ -13,8 +13,8 @@
/// Number of milliseconds per cycle /** Number of milliseconds per cycle */
const int CYCLE_MILLISECONDS = 100; #define CYCLE_MILLISECONDS 100
@ -87,7 +87,7 @@ void cDeadlockDetect::Execute(void)
} Checker(this); } Checker(this);
cRoot::Get()->ForEachWorld(Checker); cRoot::Get()->ForEachWorld(Checker);
cSleep::MilliSleep(CYCLE_MILLISECONDS); std::this_thread::sleep_for(std::chrono::milliseconds(CYCLE_MILLISECONDS));
} // while (should run) } // while (should run)
} }
@ -119,7 +119,7 @@ void cDeadlockDetect::CheckWorldAge(const AString & a_WorldName, Int64 a_Age)
if (WorldAge.m_Age == a_Age) if (WorldAge.m_Age == a_Age)
{ {
WorldAge.m_NumCyclesSame += 1; WorldAge.m_NumCyclesSame += 1;
if (WorldAge.m_NumCyclesSame > (1000 * m_IntervalSec) / CYCLE_MILLISECONDS) if (WorldAge.m_NumCyclesSame > (m_IntervalSec * 1000) / CYCLE_MILLISECONDS)
{ {
DeadlockDetected(); DeadlockDetected();
} }

@ -28,7 +28,7 @@ class cDeadlockDetect :
public: public:
cDeadlockDetect(void); cDeadlockDetect(void);
/// Starts the detection. Hides cIsThread's Start, because we need some initialization /** Starts the detection. Hides cIsThread's Start, because we need some initialization */
bool Start(int a_IntervalSec); bool Start(int a_IntervalSec);
protected: protected:

@ -11,7 +11,6 @@
#include "../BlockEntities/BlockEntity.h" #include "../BlockEntities/BlockEntity.h"
#include "../BlockEntities/EnderChestEntity.h" #include "../BlockEntities/EnderChestEntity.h"
#include "../Root.h" #include "../Root.h"
#include "../OSSupport/Timer.h"
#include "../Chunk.h" #include "../Chunk.h"
#include "../Items/ItemHandler.h" #include "../Items/ItemHandler.h"
#include "../Vector3.h" #include "../Vector3.h"
@ -27,7 +26,7 @@
#define PLAYER_INVENTORY_SAVE_INTERVAL 6000 #define PLAYER_INVENTORY_SAVE_INTERVAL 6000
// 1000 = once per second // 1000 = once per second
#define PLAYER_LIST_TIME_MS 1000 #define PLAYER_LIST_TIME_MS std::chrono::milliseconds(1000)
@ -91,9 +90,7 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) :
SetMaxHealth(MAX_HEALTH); SetMaxHealth(MAX_HEALTH);
m_Health = MAX_HEALTH; m_Health = MAX_HEALTH;
cTimer t1; m_LastPlayerListTime = std::chrono::steady_clock::now();
m_LastPlayerListTime = t1.GetNowTime();
m_PlayerName = a_PlayerName; m_PlayerName = a_PlayerName;
cWorld * World = NULL; cWorld * World = NULL;
@ -264,11 +261,10 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk)
m_Inventory.UpdateItems(); m_Inventory.UpdateItems();
// Send Player List (Once per m_LastPlayerListTime/1000 ms) // Send Player List (Once per m_LastPlayerListTime/1000 ms)
cTimer t1; if (m_LastPlayerListTime + PLAYER_LIST_TIME_MS <= std::chrono::steady_clock::now())
if (m_LastPlayerListTime + PLAYER_LIST_TIME_MS <= t1.GetNowTime())
{ {
m_World->BroadcastPlayerListUpdatePing(*this); m_World->BroadcastPlayerListUpdatePing(*this);
m_LastPlayerListTime = t1.GetNowTime(); m_LastPlayerListTime = std::chrono::steady_clock::now();
} }
if (IsFlying()) if (IsFlying())

@ -516,7 +516,7 @@ protected:
/** The item being dragged by the cursor while in a UI window */ /** The item being dragged by the cursor while in a UI window */
cItem m_DraggingItem; cItem m_DraggingItem;
long long m_LastPlayerListTime; std::chrono::steady_clock::time_point m_LastPlayerListTime;
cClientHandle * m_ClientHandle; cClientHandle * m_ClientHandle;

@ -257,7 +257,6 @@ template class SizeChecker<UInt16, 2>;
#ifndef TEST_GLOBALS #ifndef TEST_GLOBALS
// Common headers (part 1, without macros): // Common headers (part 1, without macros):
#include "StringUtils.h" #include "StringUtils.h"
#include "OSSupport/Sleep.h"
#include "OSSupport/CriticalSection.h" #include "OSSupport/CriticalSection.h"
#include "OSSupport/Semaphore.h" #include "OSSupport/Semaphore.h"
#include "OSSupport/Event.h" #include "OSSupport/Event.h"

@ -13,7 +13,6 @@ SET (SRCS
IsThread.cpp IsThread.cpp
ListenThread.cpp ListenThread.cpp
Semaphore.cpp Semaphore.cpp
Sleep.cpp
Socket.cpp Socket.cpp
SocketThreads.cpp SocketThreads.cpp
Timer.cpp) Timer.cpp)
@ -28,7 +27,6 @@ SET (HDRS
ListenThread.h ListenThread.h
Queue.h Queue.h
Semaphore.h Semaphore.h
Sleep.h
Socket.h Socket.h
SocketThreads.h SocketThreads.h
Timer.h) Timer.h)

@ -33,7 +33,7 @@ protected:
volatile bool m_ShouldTerminate; volatile bool m_ShouldTerminate;
public: public:
cIsThread(const AString & iThreadName); cIsThread(const AString & a_ThreadName);
virtual ~cIsThread(); virtual ~cIsThread();
/// Starts the thread; returns without waiting for the actual start /// Starts the thread; returns without waiting for the actual start

@ -1,19 +0,0 @@
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#ifndef _WIN32
#include <unistd.h>
#endif
void cSleep::MilliSleep( unsigned int a_MilliSeconds)
{
#ifdef _WIN32
Sleep(a_MilliSeconds); // Don't tick too much
#else
usleep(a_MilliSeconds*1000);
#endif
}

@ -1,7 +0,0 @@
#pragma once
class cSleep
{
public:
static void MilliSleep( unsigned int a_MilliSeconds);
};

@ -1,37 +0,0 @@
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Timer.h"
cTimer::cTimer(void)
{
#ifdef _WIN32
QueryPerformanceFrequency(&m_TicksPerSecond);
#endif
}
long long cTimer::GetNowTime(void)
{
#ifdef _WIN32
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return ((now.QuadPart * 1000) / m_TicksPerSecond.QuadPart);
#else
struct timeval now;
gettimeofday(&now, NULL);
return (long long)now.tv_sec * 1000 + (long long)now.tv_usec / 1000;
#endif
}

@ -1,32 +0,0 @@
// Timer.h
// Declares the cTimer class representing an OS-independent of retrieving current time with msec accuracy
#pragma once
class cTimer
{
public:
cTimer(void);
// Returns the current time expressed in milliseconds
long long GetNowTime(void);
private:
#ifdef _WIN32
LARGE_INTEGER m_TicksPerSecond;
#endif
} ;

@ -16,7 +16,6 @@
#include "Protocol/ProtocolRecognizer.h" // for protocol version constants #include "Protocol/ProtocolRecognizer.h" // for protocol version constants
#include "CommandOutput.h" #include "CommandOutput.h"
#include "DeadlockDetect.h" #include "DeadlockDetect.h"
#include "OSSupport/Timer.h"
#include "LoggerListeners.h" #include "LoggerListeners.h"
#include "BuildInfo.h" #include "BuildInfo.h"
@ -118,9 +117,7 @@ void cRoot::Start(void)
m_bStop = false; m_bStop = false;
while (!m_bStop) while (!m_bStop)
{ {
cTimer Time; auto BeginTime = std::chrono::steady_clock::now();
long long mseconds = Time.GetNowTime();
m_bRestart = false; m_bRestart = false;
LoadGlobalSettings(); LoadGlobalSettings();
@ -200,17 +197,14 @@ void cRoot::Start(void)
} }
#endif #endif
long long finishmseconds = Time.GetNowTime(); LOG("Startup complete, took %lld ms!", std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - BeginTime).count());
finishmseconds -= mseconds;
LOG("Startup complete, took %lld ms!", finishmseconds);
#ifdef _WIN32 #ifdef _WIN32
EnableMenuItem(hmenu, SC_CLOSE, MF_ENABLED); // Re-enable close button EnableMenuItem(hmenu, SC_CLOSE, MF_ENABLED); // Re-enable close button
#endif #endif
while (!m_bStop && !m_bRestart && !m_TerminateEventRaised) // These are modified by external threads while (!m_bStop && !m_bRestart && !m_TerminateEventRaised) // These are modified by external threads
{ {
cSleep::MilliSleep(1000); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
if (m_TerminateEventRaised) if (m_TerminateEventRaised)

@ -4,7 +4,6 @@
#include "Server.h" #include "Server.h"
#include "ClientHandle.h" #include "ClientHandle.h"
#include "OSSupport/Timer.h"
#include "Mobs/Monster.h" #include "Mobs/Monster.h"
#include "OSSupport/Socket.h" #include "OSSupport/Socket.h"
#include "Root.h" #include "Root.h"
@ -73,22 +72,19 @@ cServer::cTickThread::cTickThread(cServer & a_Server) :
void cServer::cTickThread::Execute(void) void cServer::cTickThread::Execute(void)
{ {
cTimer Timer; auto LastTime = std::chrono::steady_clock::now();
static const auto msPerTick = std::chrono::milliseconds(50);
long long msPerTick = 50;
long long LastTime = Timer.GetNowTime();
while (!m_ShouldTerminate) while (!m_ShouldTerminate)
{ {
long long NowTime = Timer.GetNowTime(); auto NowTime = std::chrono::steady_clock::now();
float DeltaTime = (float)(NowTime-LastTime); m_ShouldTerminate = !m_Server.Tick(std::chrono::duration_cast<std::chrono::milliseconds>(NowTime - LastTime).count());
m_ShouldTerminate = !m_Server.Tick(DeltaTime); auto TickTime = std::chrono::steady_clock::now() - NowTime;
long long TickTime = Timer.GetNowTime() - NowTime;
if (TickTime < msPerTick) if (TickTime < msPerTick)
{ {
// Stretch tick time until it's at least msPerTick // Stretch tick time until it's at least msPerTick
cSleep::MilliSleep((unsigned int)(msPerTick - TickTime)); std::this_thread::sleep_for(msPerTick -TickTime);
} }
LastTime = NowTime; LastTime = NowTime;

@ -11,7 +11,6 @@
#include "inifile/iniFile.h" #include "inifile/iniFile.h"
#include "ChunkMap.h" #include "ChunkMap.h"
#include "Generating/ChunkDesc.h" #include "Generating/ChunkDesc.h"
#include "OSSupport/Timer.h"
#include "SetChunkData.h" #include "SetChunkData.h"
// Serializers // Serializers
@ -109,7 +108,7 @@ protected:
// Wait for 2 sec, but be "reasonably wakeable" when the thread is to finish // Wait for 2 sec, but be "reasonably wakeable" when the thread is to finish
for (int i = 0; i < 20; i++) for (int i = 0; i < 20; i++)
{ {
cSleep::MilliSleep(100); std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (m_ShouldTerminate) if (m_ShouldTerminate)
{ {
return; return;
@ -159,7 +158,7 @@ protected:
// Wait for 2 sec, but be "reasonably wakeable" when the thread is to finish // Wait for 2 sec, but be "reasonably wakeable" when the thread is to finish
for (int i = 0; i < 20; i++) for (int i = 0; i < 20; i++)
{ {
cSleep::MilliSleep(100); std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (m_ShouldTerminate) if (m_ShouldTerminate)
{ {
return; return;
@ -167,7 +166,6 @@ protected:
} }
} // for (-ever) } // for (-ever)
} }
}; };
@ -201,23 +199,20 @@ cWorld::cTickThread::cTickThread(cWorld & a_World) :
void cWorld::cTickThread::Execute(void) void cWorld::cTickThread::Execute(void)
{ {
cTimer Timer; auto LastTime = std::chrono::steady_clock::now();
static const auto msPerTick = std::chrono::milliseconds(50);
auto TickTime = std::chrono::steady_clock::duration(50);
const Int64 msPerTick = 50;
Int64 LastTime = Timer.GetNowTime();
Int64 TickDuration = 50;
while (!m_ShouldTerminate) while (!m_ShouldTerminate)
{ {
Int64 NowTime = Timer.GetNowTime(); auto NowTime = std::chrono::steady_clock::now();
float DeltaTime = (float)(NowTime - LastTime); m_World.Tick(std::chrono::duration_cast<std::chrono::milliseconds>(NowTime - LastTime).count(), std::chrono::duration_cast<std::chrono::duration<int>>(TickTime).count());
m_World.Tick(DeltaTime, (int)TickDuration); TickTime = std::chrono::steady_clock::now() - NowTime;
TickDuration = Timer.GetNowTime() - NowTime;
if (TickDuration < msPerTick) if (TickTime < msPerTick)
{ {
// Stretch tick time until it's at least msPerTick // Stretch tick time until it's at least msPerTick
cSleep::MilliSleep((unsigned int)(msPerTick - TickDuration)); std::this_thread::sleep_for(msPerTick -TickTime);
} }
LastTime = NowTime; LastTime = NowTime;

@ -160,7 +160,10 @@ BOOL CtrlHandler(DWORD fdwCtrlType)
if (fdwCtrlType == CTRL_CLOSE_EVENT) // Console window closed via 'x' button, Windows will try to close immediately, therefore... if (fdwCtrlType == CTRL_CLOSE_EVENT) // Console window closed via 'x' button, Windows will try to close immediately, therefore...
{ {
while (!g_ServerTerminated) { cSleep::MilliSleep(100); } // Delay as much as possible to try to get the server to shut down cleanly while (!g_ServerTerminated)
{
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // Delay as much as possible to try to get the server to shut down cleanly
}
} }
return TRUE; return TRUE;