Odd Sleep() Within Thread Behavior
I have a thread that I use to update information 50 times a second. To make sure it updates at that I measure how long it took to update the info, and then subtract that from 20 (1/50 = 20 milliseconds) to get the time remaining that I need to sleep for. If it took longer than 20 milliseconds to update, it does not sleep at all. The problem comes in that every so often the application will sleep longer than it should, usually around 30-32 milliseconds, and this throws off the updating. Even if I remove all updating calculations the sleep function still sleeps longer than it should. I have been using GetSystemTime() to get the milliseconds, and it has worked as it should. Below is some pseudo-code of what my thread looks like. I have tried using CreateThread() and _beginthread() but it doesn't change anything (I didn't expect it to but worth a try). Looking at the task manager under both the correct sleep time, and the 30+ms sleep time the cpu percentage and memory usage are the same, if it makes a difference.
Code:
void __stdcall mythread(void* param)
{
while(true)
{
GetSystemTime(&starttime);
// do updating info, but this is commented out and it still sleeps too long
GetSystemTime(&endtime);
GetSystemTime(&starttime2);
if (endtime - starttime < 20 milliseconds)
{
Sleep(20 - (endtime - starttime));
}
GetSystemTime(&endtime2);
// here is where endtime2 - starttime2 reports being more than 30ms
}