Click to See Complete Forum and Search --> : The undying thread, maybe


lsvedin
December 7th, 2004, 03:22 PM
I have the following code

#define END_THREAD 0x9000

MyApp.h
class CMyApp: public CWinApp
{
public:
<snip>

CThreadOne *m_pThreadOne;
CThreadTwo *m_pThreadTwo;

//}}AFX_MSG
afx_msg LRESULT TerminateApp(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()

<snip>>
};

MyApp.cpp
BOOL CMyApp::InitInstance()
{
<snip>
m_pThreadOne= (CThreadOne*)AfxBeginThread(RUNTIME_CLASS(CThreadOne));
m_pThreadTwo= (CThreadTwo *)AfxBeginThread(RUNTIME_CLASS(CThreadTwo ));
<snip>
}



LRESULT CMyApp::TerminateApp(WPARAM wParam, LPARAM lParam){

m_pThreadOne->PostThreadMessage(END_THREAD, NULL, NULL);
::WaitForSingleObject(m_pThreadOne->m_hThread, INFINITE);
m_pThreadTwo->PostThreadMessage(END_THREAD, NULL, NULL);
::WaitForSingleObject(m_pThreadTwo->m_hThread, INFINITE);

m_pMainWnd->PostMessage(WM_CLOSE);
return(0);
}


CThreadOne.cpp

BEGIN_MESSAGE_MAP(CThreadOne, CWinThread)
//{{AFX_MSG_MAP(CThreadOne)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
ON_THREAD_MESSAGE(END_THREAD, EndThread)
END_MESSAGE_MAP()


LRESULT CThreadOne::EndThread(WPARAM wParam, LPARAM lParam)
{
AfxEndThread(0);
return(0);
}




Everything in hunky dory until it gets to the WaitForSingleObject and then the wait truly becomes INFINITE.

If I replace END_THREAD with WM_QUIT, everything closes down nice and proper like.

What am I doing wrong?

MikeAThon
December 7th, 2004, 05:53 PM
Sorry to ask the obvious, but did you also define a handler for END_THREAD in CThreadTwo (your code only shows a handler for CThreadOne)?

That aside, why did you use PostThreadMessage instead of a simple PostMessage? There are some issues with PostThreadMessage that don't arise with PostMessage, and since both threads are running a message loop, I think you're fine with PostMessage.

Mike