Question

I am not an MFC expert, and definately not a multithread expert but still, I want to understand this strange behavior. At some places when I create an MFC ui thread in my application it is started and can display a messagebox no problem, with the main ui thread blocked. However sometimes if I create the thread, then the thread execution stops until the main ui thread non-blocked again.

Of course the situation is made up. The main ui thread's blocking, symbolizes some kind of synchronisation, while the ui thread's messagebox symbolizes some more complex ui dialog.

This is more of a theoretical question. I am primary interested in the reason why this could happen? Here is an example :

class MessageBoxThread : public CWinThread
{
    DECLARE_DYNCREATE( MessageBoxThread );
public:
    virtual BOOL InitInstance()
    {
        CWinThread::InitInstance();
        AfxMessageBox(_T("Some text"));
        return TRUE;
    }
};

IMPLEMENT_DYNCREATE( MessageBoxThread , CWinThread );


void testing()
{
    MessageBoxThread* pMessageBoxThread = new MessageBoxThread ();
    pMessageBoxThread->CreateThread();

    Sleep(10000);

    AfxMessageBox(_T("It Worked!"));
}

So in terms of the example, if I put 'testing' function into CWinApp::InitInstance it is working as expected (showing 'Some text' first then after 10 sec showing 'It Worked!'). However if I put it into a random place deep inside my application, it might happen that the two messageboxes appear at the same time after the 10 sec sleep. What could cause such behavior?

Was it helpful?

Solution 2

Okay, I finally found the answer. When someone creates a ui thread, that person must initialize the m_pMainWnd member which contains the ui threads base window. If you fail to do so, the framework will use the application provided main window, which is the one in the main ui thread. Since that one is blocked because of the Sleep() method, the other ui thread will only respond when the main thread is not blocked.

OTHER TIPS

I am not an MFC fan, but knowing Win32 I can see what is happening. By putting it "deep" you probably mean calling the testing() function in some window message processing code - a code that runs on the main UI thread and processes pumped messages. So you are putting your UI thread to sleep which in this case is similar to what a message box or a modal dialog would do. So, your message pump (implemented in CWinApp I think) is blocked by this Sleep() waiting you to complete processing the message in response to which your code is executed (does not matter what message).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top