Win32多線程的建立方法主要有:html
CreateThread()編程
_beginthread()&&_beginthreadex()
windows
AfxBeginThread()
多線程
CWinThread類app
CreateThread: Win32提供的建立線程的最基礎的API,用於在主線程上建立一個線程。返回一個HANDLE句柄(內核對象)。在內核對象使用完畢後,通常須要關閉,使用CloseHandle()函數。less
_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建立線程,不然會內存泄漏「的來源了。this
更詳細的介紹見http://wenku.baidu.com/view/adede4ec4afe04a1b071dea4.htmlspa
也就是說:儘可能用_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(輸出參數)