Loops in WinApi program?

Hello everybody!

Let's say I'd like to make program that does sth with a file when I click a button. To do sth with that file I need a loop(I want to read and process every line of the file). How should I place that loop in my WinApi program, so that I don't block message loop? Should I maybe use threads?
You could use a separate thread -- or you could periodically pump the message queue from within your loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
int linesUntilNextPump = 4000;
for( ...each line of the file... )
{
    // ... do processing

    --linesUntilNextPump;
    if(linesUntilNextPump <= 0)
    {
        linesUntilNextPump = 4000;
        pumpMessageQueue();  // ie, call PeekMessage/TranslateMessage/DispatchMessage
           // until no more messages in queue
    }
}
Thank you. I think I'll go with threads, this way it will work no matter how long processing takes.
Be careful with threads. Keep in mind that any data shared between multiple threads has to be guarded behind some kind of synchronization mechanism (typically a mutex).

Multithreading in C++ is actually extremely tricky. If you aren't very careful, it's easy to screw up and have it cause really hard to find and really hard to fix bugs.
If your processing is in response to interaction with some visual control such as a button, then your app won't retrieve any more messages from the message quene until processing is complete. So the UI will become unresponsive. Folks used to talk about the 0.1 second rule, that is, if processing is expected to take more than one tenth of a second - use a seperate thread. I personally think that could be increased to one second or so, but the thing is, its hard to estimate how long something will take, especially if network access is involved.

I have not had any difficulties using worker threads, but I'm hard core about not using global variables in my programs. That seems to eliminate the need to be constantly guarding data with mutexes, which tends to bloat and over-complicate the code.
Remember, when using worker threads in a Win32 app don't touch the GUI! or you can end up in a serious deadlock situation. However you can post messages to your application's message queue from another thread.

Here's an old but very useful guide on using worker threads safely in a Win32 app: http://www.flounder.com/workerthreads.htm

*Edit: That article is actually based on MFC but it should be fairly trivial to apply the concepts
Last edited on
Topic archived. No new replies allowed.