Feb 202011

Occasionally I want to yield a tight loop to allow messages from the GUI to be updated.  One way to do this is to put the loop processing in a thread, but if I don’t want to go to that trouble for something really simple, I sometimes just call this function at a safe place in the loop.

//
// Release main thread for background processing
//
void GiveTime()
{
	// Idle until the screen redraws itself, et. al.
	MSG msg;
	while (::PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) ) {
		if (!AfxGetThread()->PumpMessage( )) {
			::PostQuitMessage(0);
			break;
		}
	}
	// let MFC do its idle processing
	LONG lIdle = 0;
	while (AfxGetApp()->OnIdle(lIdle++ ))
		;
}

For example:

for(int i = 0; i < 1000000; ++i) {
    // Do something
    GiveTime();
}

You may also want to throttle how often this happens to help the loop run faster.

for(int i = 0; i < 1000000; ++i) {
    // Do something
    if((i % 1000) == 0)
        GiveTime();
}

Leave a Reply

(required)

(required)