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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值