结束线程使用函数_endthreadex函数,释放掉线程的tiddata数据块。
CreateThread、_beginthread和_beginthreadex都是用来启动线程的,但大家看到oldworm没有提供_beginthread的方式,原因简单,_beginthread是_beginthreadex的功能子集,虽然_beginthread内部是调用_beginthreadex但他屏蔽了象安全特性这样的功能,所以_beginthread与CreateThread不是同等级别,_beginthreadex和CreateThread在功能上完全可替代,我们就来比较一下_beginthreadex与CreateThread!
CRT的函数库在线程出现之前就已经存在,所以原有的CRT不能真正支持线程,这导致我们在编程的时候有了CRT库的选择,在MSDN中查阅CRT的函数时都有:
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
这样的提示!
对于线程的支持是后来的事!
这也导致了许多CRT的函数在多线程的情况下必须有特殊的支持,不能简单的使用CreateThread就OK。
大多的CRT函数都可以在CreateThread线程中使用,看资料说只有signal()函数不可以,会导致进程终止!但可以用并不是说没有问题!
有些CRT的函数象malloc(), fopen(), _open(), strtok(), ctime(), 或localtime()等函数需要专门的线程局部存储的数据块,这个数据块通常需要在创建线程的时候就建立,如果使用CreateThread,这个数据块就没有建立,然后会怎样呢?在这样的线程中还是可以使用这些函数而且没有出错,实际上函数发现这个数据块的指针为空时,会自己建立一个,然后将其与线程联系在一起,这意味着如果你用CreateThread来创建线程,然后使用这样的函数,会有一块内存在不知不觉中创建,遗憾的是,这些函数并不将其删除,而CreateThread和ExitThread也无法知道这件事,于是就会有Memory Leak,在线程频繁启动的软件中(比如某些服务器软件),迟早会让系统的内存资源耗尽!
_beginthreadex(内部也调用CreateThread)和_endthreadex就对这个内存块做了处理,所以没有问题!(不会有人故意用CreateThread创建然后用_endthreadex终止吧,而且线程的终止最好不要显式的调用终止函数,自然退出最好!)
谈到Handle的问题,_beginthread的对应函数_endthread自动的调用了CloseHandle,而_beginthreadex的对应函数_endthreadex则没有,所以CloseHandle无论如何都是要调用的不过_endthread可以帮你执行自己不必写,其他两种就需要自己写!(Jeffrey Richter强烈推荐尽量不用显式的终止函数,用自然退出的方式,自然退出当然就一定要自己写CloseHandle)
CreateThread用法:
The calling thread uses the WaitForMultipleObjects function to persist until all worker threads have terminated. Note that if you were to close the handle to a worker thread before it terminated, this does not terminate the worker thread. However, the handle will be unavailable for use in subsequent function calls.
#include <windows.h> #include <strsafe.h> #define MAX_THREADS 3 #define BUF_SIZE 255 typedef struct _MyData { int val1; int val2; } MYDATA, *PMYDATA; DWORD WINAPI ThreadProc( LPVOID lpParam ) { HANDLE hStdout; PMYDATA pData; TCHAR msgBuf[BUF_SIZE]; size_t cchStringSize; DWORD dwChars; hStdout = GetStdHandle(STD_OUTPUT_HANDLE); if( hStdout == INVALID_HANDLE_VALUE ) return 1; // Cast the parameter to the correct data type. pData =0 (PMYDATA)lpParam; // Print the parameter values using thread-safe functions. StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d\n"), pData->val1, pData->val2); StringCchLength(msgBuf, BUF_SIZE, &cchStringSize); WriteConsole(hStdout, msgBuf, cchStringSize, &dwChars, NULL); // Free the memory allocated by the caller for the thread // data structure. HeapFree(GetProcessHeap(), 0, pData); return 0; } void main() { PMYDATA pData; DWORD dwThreadId[MAX_THREADS]; HANDLE hThread[MAX_THREADS]; int i; // Create MAX_THREADS worker threads. for( i=0; i<MAX_THREADS; i++ ) { // Allocate memory for thread data. pData = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MYDATA)); if( pData == NULL ) ExitProcess(2); // Generate unique data for each thread. pData->val1 = i; pData->val2 = i+100; hThread[i] = CreateThread( NULL, // default security attributes 0, // use default stack size ThreadProc, // thread function pData, // argument to thread function 0, // use default creation flags &dwThreadId[i]); // returns the thread identifier // Check the return value for success. if (hThread[i] == NULL) { ExitProcess(i); } } // Wait until all threads have terminated. WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE); // Close all thread handles upon completion. for(i=0; i<MAX_THREADS; i++) { CloseHandle(hThread[i]); } }
_beginthreadEX用法:
// crt_begthrdex.cpp // compile with: /MT #include <windows.h> #include <stdio.h> #include <process.h> unsigned Counter; unsigned __stdcall SecondThreadFunc( void* pArguments ) { printf( "In second thread...\n" ); while ( Counter < 1000000 ) Counter++; _endthreadex( 0 ); return 0; } int main() { HANDLE hThread; unsigned threadID; printf( "Creating second thread...\n" ); // Create the second thread. hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID ); // Wait until second thread terminates. If you comment out the line // below, Counter will not be correct because the thread has not // terminated, and Counter most likely has not been incremented to // 1000000 yet. WaitForSingleObject( hThread, INFINITE ); printf( "Counter should be 1000000; it is-> %d\n", Counter ); // Destroy the thread object. CloseHandle( hThread ); }