Skip to content

True Wait

A C helper that performs a timed wait on a background thread, flipping a flag when the interval elapses so the caller can keep working meanwhile.

Published Jan 5, 1995

A sleep that does not sleep your program. TrueWait spawns a worker thread that sleeps for the requested number of milliseconds and then sets a shared WaitFlag; the calling thread keeps running (here, printing in a loop) and checks the flag whenever it wants to know whether the interval has passed. It is the classic pre-event pattern for "wait N ms but stay responsive" - useful in console tools, installers, or anywhere you need a delay without freezing the UI thread. Modern code would usually use a named event with WaitForSingleObject(handle, timeout) instead, but this shows the underlying idea clearly.

////////////////////////////////////////////////////////////////////////

void TrueWait(DWORD);
DWORD WINAPI Wait_Thread(LPVOID);

////////////////////////////////////////////////////////////////////////

struct WaitThread{
    HANDLE Wait_Thread_Handle;
    long Wait_Thread_ID;
    BOOL WaitFlag;
}; struct WaitThread WT;

////////////////////////////////////////////////////////////////////////

void TrueWait(DWORD WaitTime)
{
    WT.Wait_Thread_Handle = CreateThread(NULL,0,Wait_Thread,(LPVOID)WaitTime,0,&WT.Wait_Thread_ID);
}

////////////////////////////////////////////////////////////////////////

DWORD WINAPI Wait_Thread(LPVOID WaitTime)
{
    WT.WaitFlag = FALSE;
    sleep((DWORD)WaitTime);
    WT.WaitFlag = TRUE;
    return((DWORD)WaitTime);
}
#include <Windows.H>
#include <WindowsX.H>
#include <Stdio.H>
#include <Stdlib.H>
#include <string.h>

#include "TrueWait.H"

//////////////////////////////////////////////////////////////////////

int main()
{
	TrueWait(3000);

	while(WT.WaitFlag == FALSE)
		printf("Looping. %d\n",WT.WaitFlag);

	return 0;
}

Two caveats carried over from the original: passing an integer through LPVOID only works cleanly on 32-bit builds (use a pointer to a DWORD, or set _W64-aware casts, on 64-bit), and the flag should be declared volatile (or accessed atomically) since two threads read and write it - here the GCC/MSVC compilers will likely get away with it, but it is technically a data race.

An unhandled error has occurred. Reload 🗙