Implementation of thread-safe GetTickCount64 for Windows XP

I focus on Windows XP, and I need a function like GetTickCount64 that does not overflow.

I could not find a suitable solution that would be correct and thread safe, so I tried to roll my own.

Here is what I came up with:

ULONGLONG MyGetTickCount64(void) { static volatile DWORD dwHigh = 0; static volatile DWORD dwLastLow = 0; DWORD dwTickCount; dwTickCount = GetTickCount(); if(dwTickCount < (DWORD)InterlockedExchange(&dwLastLow, dwTickCount)) { InterlockedIncrement(&dwHigh); } return (ULONGLONG)dwTickCount | (ULONGLONG)dwHigh << 32; } 

Is it really thread safe?

Thread safety is difficult to verify for correctness, so Iโ€™m not sure if it is really correct in all cases.

+6
source share
1 answer

On Windows, the timer overflow problem is usually resolved (in games) using the QueryPerformanceCounter() functions instead of GetTickCount() :

 double GetCycles() const { LARGE_INTEGER T1; QueryPerformanceCounter( &T1 ); return static_cast<double>( T1.QuadPart ); } 

Then you can multiply this number by the inverse of the number of cycles per second to convert cycles to seconds:

 void Initialize() { LARGE_INTEGER Freq; QueryPerformanceFrequency( &Freq ); double CyclesPerSecond = static_cast<double>( Freq.QuadPart ); RecipCyclesPerSecond = 1.0 / CyclesPerSecond; } 

After initialization, this code is thread safe:

 double GetSeconds() const { return GetCycles() * RecipCyclesPerSecond; } 

You can also check the full source code (portable between Windows and many other platforms) from our open Linderdaum Engine: http://www.linderdaum.com

+4
source

Source: https://habr.com/ru/post/949932/


All Articles