Win32多线程的创建方法主要有:
CreateThread()
_beginthread()&&_beginthreadex()
AfxBeginThread()
CWinThread类
一、简介
CreateThread: Win32提供的创建线程的最基础的API,用于在主线程上创建一个线程。返回一个HANDLE句柄(内核对象)。在内核对象使用完毕后,一般需要关闭,使用CloseHandle()函数。
_beginthread()&&_beginthreadex():
在MSDN中可以看到一句很重要的提示,内容为“For an executable file linked with Libcmt.lib, do not call the Win32 ExitThread API; this prevents the run-time system from reclaiming allocated resources. _endthread and _endthreadex reclaim allocated thread resources and then call ExitThread.”,简单翻译就是说,对于链接Libcmt.lib的可执行程序,不要使用Win32的线程退出函数(ExitThread),这会阻止运行时系统回收分配的资源,应该使用_endthread,它能回收分配的线程资源然后调用ExitThread。这个问题看似没有提到CreateThread(),但是其实有关,这就是经常看到有些资料上坚决的说到”不要使用CreateThread创建线程,否则会内存泄漏“的来源了。
更详细的介绍见
也就是说:尽量用_beginthread()而不是CreateThread
Windows核心编程上如此说:
These two functions were originally created to do the work of the new _beginthreadex and _endthreadex functions, respectively. However, as you can see, the _beginthread function has fewer parameters and is therefore more limited than the full-featured _beginthreadex function. For example, if you use _beginthread, you cannot create the new thread with security attributes, you cannot create the thread suspended, and you cannot obtain the thread's ID value. The _endthread function has a similar story: it takes no parameters, which means that the thread's exit code is hardcoded to 0.
_endthread还有个问题:
DWORD dwExitCode;HANDLE hThread = _beginthread(...);GetExitCodeThread(hThread, &dwExitCode);CloseHandle(hThread);
The newly created thread might execute, return, and terminate before the first thread can call GetExitCodeThread. If this happens, the value in hThread will be invalid because _endthread has closed the new thread's handle. Needless to say, the call to CloseHandle will also fail for the same reason.
简单翻译为: 在调用GetExitCodeThread之前,可能新创建的线程已经执行,返回并终止了,这个时候,hThread将无效,_endthread已经关掉了线程句柄。
_beginthreadex > _beginthread > CreateThread
AfxBeginThread:这是MFC中的Afx系列函数,一个在MFC中创建线程的全局函数。
封装了_beginthreadex,因此,MFC程序,尽量用该函数。
CWinThread:UI线程,能接收消息,需要调用AfxBeginThread创建线程。
AfxBeginThread(RUNTIME_CLASS(MyThread))
二、部分参数介绍
dwStackSize:线程堆栈大小,使用0采用默认设置,默认为1024K,所以默认只能创建不到2048个线程(2G内存).windows会根据需要动态增加堆栈大小。
lpThreadAttributes:线程属性。
lpStartAddress:指向线程函数的指针。
lpParameter:向线程函数传递的参数。
dwCreationFlags:线程标志,CREATE_SUSPENDED表示创建一个挂起的线程,0表示创建后立即激活线程。
lpThreadId,先线程的ID(输出参数)