mfc中主线程是WinMain还是CWinThread派生的应用程序类CWinApp中的线程

2025-04-08 20:04:00
推荐回答(2个)
回答1:

MFC通过类、宏进行了层层封装,搞的神秘兮兮,很容易绕晕。但好在大多数功能都有源代码,只要耐心看,总可以追溯。

首先,你的提问中,CWinThread的工作函数不是WinMain,而是Run。其次,如果讨论界定在MFC的标准主线程,那么这是很明确的,同样是Run函数。

CWinApp是MFC主线程的标准类,派生后的APP类,从InitInstance进入,之后进入了CWinApp类的Run:

int CWinApp::Run()
{
if (m_pMainWnd == NULL && AfxOleGetUserCtrl())
{
// Not launched /Embedding or /Automation, but has no main window!
TRACE0("Warning: m_pMainWnd is NULL in CWinApp::Run - quitting application.\n");
AfxPostQuitMessage(0);
}
return CWinThread::Run();
}

这里调用了基类的Run函数,实际就是启动了主工作函数CWinThread::Run,这个函数的代码如下:

int CWinThread::Run()
{
ASSERT_VALID(this);

// for tracking the idle time state
BOOL bIdle = TRUE;
LONG lIdleCount = 0;

// acquire and dispatch messages until a WM_QUIT message is received.
for (;;)
{
// phase1: check to see if we can do idle work
while (bIdle &&
!::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE))
{
// call OnIdle while in bIdle state
if (!OnIdle(lIdleCount++))
bIdle = FALSE; // assume "no idle" state
}

// phase2: pump messages while available
do
{
// pump message, but quit on WM_QUIT
if (!PumpMessage())
return ExitInstance();

// reset "no idle" state after pumping "normal" message
if (IsIdleMessage(&m_msgCur))
{
bIdle = TRUE;
lIdleCount = 0;
}

} while (::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE));
}

ASSERT(FALSE);  // not reachable
}

在MFC程序中,AfxWinMain实际上只是起到了“承接”的作用,串联了APP类的几个函数,并不是真正的工作函数。

回答2:

我同意你的意见,我感觉 CWinThread在MFC并未发挥创建线程的功能,仅仅是提供了几个函数比如Run给WinMain调用而已,并未产生新线程!这个里面有MFC的视频课程是这么讲解的: