Throwing the good doctor for a loop…

Dear Dr. GUI,

Is it possible to drop into an endless loop yet keep the Windows message loop pumping? I’ve always been told that this isn’t possible, but hey, you’re Dr. GUI… perhaps by making appropriate (API or MFC) function calls from within the loop it is possible.

Let’s assume I have a good reason (which I don’t!) for wanting to do this. I realize that normally a timer loop (calling OnTimer()) would be used instead of the endless loop.

Steven D. Lacy

Dr. GUI replies:

Kind of a loopy question, no? Note that this is actually a common problem: any operation, such as background printing, file I/O, or network I/O, that you’d like to run in the background will need to keep the message pump going.

Well, there are a couple of ways to do this. Under Win32, the best way is to just spawn a new thread so that your “infinite loop” is run in a separate thread from the thread running the message pump. This thread should probably be a worker thread—it shouldn’t create any UI elements. And don’t set the priority of this background thread too high or you’ll starve the system, okay? Multithreaded programming brings up a lot of tough issues—read about them in the Win32 SDK documentation. Note also that MFC supports multithreaded programming. Finally, note that the thread will be killed when your process exits.

Windows® 3.1x doesn’t support multiple threads, so you can’t spawn another thread to solve the problem. Therefore, you mustn’t go into an infinite loop, or you’ll lock up the whole system. However, you can do background processing by writing a loop that, in addition to your background processing, frequently calls PeekMessage to check for messages that are waiting. When it gets messages, it must dispatch them. This non-preemptive multitasking will result in jerky, slow performance, but it will work. You can do this under Win32 as well, but I don’t recommend it unless it’s just extraordinarily difficult to make your code safe for multiple threads.

And, in keeping with our Java theme: if you’re programming in Java, rejoice—multithreaded support is built into the Java language. You still have to deal with the tough issues of more than one thread modifying data at the same time, but you at least get some solid support in both the language and run-time library for doing it right.