Jonathan
Jonathan

Reputation: 489

How do I properly exit my program?

Working with C and Win32, I have a problem where my program freezes instead of closing when a quit message is posted(Alt-F4 for example), and I have to end the process with task manager.

I have this in my main loop:(problem solved)

MSG msg;
while(1)
{
    while(PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE))
    {
        if(msg.message == WM_QUIT)
        {
            terminate = 1;
            while(terminate != 3) //each thread increments "terminate" by 1 before returning
            {
                Sleep(1);
            }
            return 0;
        }
        DispatchMessage(&msg);
    }
    Sleep(1);
}

It will print "OK!" in the console and then freeze.

I think this could be because I have multiple threads and they are not terminated properly (but I read that if I return from my main() function the other threads should be killed automatically). If it helps one of those threads is an OpenGL rendering thread.

Upvotes: 1

Views: 270

Answers (2)

ComfortablyNumb
ComfortablyNumb

Reputation: 3511

Exit is to exit from the entire process. Your process will clean up when you call exit, e.g. Call the function registered with atexit, or call destructor of global object in case of c++. What about abort(), or terminateProcess.

Upvotes: 0

Femaref
Femaref

Reputation: 61467

The main function is only just a thread, you are terminating just that one. However, for a process to end, all threads need to be properly terminated or it will run forever. You'll need to keep a reference the threads and terminate them once you receive the WM_QUIT message.

Upvotes: 1

Related Questions