Search code examples
c++multithreadingsleepthread-sleep

c++ use thread as timer


I have my project with a different thread that make some stuff.

It's all ok, but I wish have some function called each 20ms (for example), but considering the time spent to the function... I try to explain better... I call the function, and the function spent 6ms to exit, so I wish that the thread sleeps 14ms (20 - 6), the next time that is called, the function spent 12ms, so the sleep will be only 8ms.... how can I do this? here is my code:

// thread constructor
DWORD dwThreadId, dwThrdParam = 1;  
HANDLE thread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)workerFunc, &dwThrdParam, 0, &dwThreadId );

// thread function
DWORD WINAPI workerFunc( LPDWORD lpdwParam )
{
    while( true )
    {
        myFunction( );
        Sleep( ??? );
    }
    return 0;
}

thanks!


Solution

  • What about this:

    clock_t start, end;
    while( true )
    {
        start = clock();
        myFunction( );
        end = clock();
        Sleep(20-(end-start)*CLOCKS_PER_SEC/1000.0);
    }