_beginthreadex CreateThread _beginthread

来源:互联网 发布:程序员眼睛疼 编辑:程序博客网 时间:2024/06/04 18:04
<<Windows核心编程>>中有很详细地介绍。 
_beginthreadex是微软的C/C++运行时库函数,CreateThread是操作系统的函数。
_beginthreadex通过调用CreateThread来实现的,但比CreateThread多做了许多工作。
注意:若要创建一个新线程,绝对不要使用CreateThread,而应使用_beginthreadex.
因为:考虑标准C运行时库的一些变量和函数,如errno,这是一个全局变量。全局变量用于
多线程会出什么事,你一定知道的了。故必须存在一种机制,使得每个线程能够引用它自己的
errno变量,又不触及另一线程的errno变量._beginthreadex就为每个线程分配自己的
tiddata内存结构。该结构保存了许多像errno这样的变量和函数的值、地址(自己看去吧)。
通过线程局部存储将tiddata与线程联系起来。具体实现在Threadex.c中有。

结束线程使用函数_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 255typedef 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 );}

0 0