MFC编程AfxBeginThread与CreateThread使用对比

MFC实际开发过程中,使用CreateThread创建的线程总是会出现莫名其妙的Bug。在参阅查找信息后,发现MFC编程,应该用AfxBeginThread来创建线程。


引语:

转自: http://blog.163.com/sky_sgx/blog/static/199439194201110944749818/
  
如果用MFC编程,不要用CreateThread,如果只是使用Runtime Library,用_BegingThread,总之,不要轻易使用CreateThread。这是因为在MFC和RTL中的函数有可能会用到些它们所封装的公用变量,也就是说AfxBeginThread和_BeginThread都有自己的启动代码是CreateThread所没有的。在用CreateThread所创建的线程中使用MFC的类和RTL函数就有可能出现问题。如果你是用汇编编写win32程序并且在线程函数中也不调用MFC和RTL的函数,那用CreateThread就没问题,或者你虽然是用C写线程函数,但你很小心没调用RTL函数也不会有问题。
  

CreateThread是由操作系统提供的接口,而AfxBeginThread和_BeginThread则是编译器对它的封装。


示例:

接下来,用具体示例来看两者间的不同。
创建支持MFC的Win32程序。
VS2005创建Win32步骤:
Win32->Win32 Console Application。
Application Settings设置(Application type: Console application,Add common header files for: MFC,Additional options: Precompiled header )。


ConsoleThreadTest.cpp

// ConsoleThreadTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "ConsoleThreadTest.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

DWORD WINAPI Proc1(LPVOID)
{
    CWinThread* pThread = AfxGetThread();
    cout<<"CreateThread::AfxGetThread";
    if (pThread != NULL)
    {
        cout<<" Valid"<<endl;
    }
    else
    {
        cout<<" NULL"<<endl;
    }

    return 1;
}

UINT Proc2(LPVOID)
{
    CWinThread* pThread = AfxGetThread();
    cout<<"AfxBeginThread::AfxGetThread";
    if (pThread != NULL)
    {
        cout<<" Valid"<<endl;
    }
    else
    {
        cout<<" NULL"<<endl;
    }

    return 1;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
	    // TODO: change error code to suit your needs
	    _tprintf(_T("Fatal Error: MFC initialization failed\n"));
	    nRetCode = 1;
    }
    else
    {
        ::CreateThread(0,0,Proc1,NULL,0,0);
        Sleep(1000);
        AfxBeginThread(Proc2,NULL);
        Sleep(1000);
    }

    return nRetCode;
}

输出结果:

CreateThread::AfxGetThread NULL
AfxBeginThread::AfxGetThread Valid

你可能感兴趣的:(多线程,mfc,mfc)