CreateThread _beginthread _beginthreadEX

<<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 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 );
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`_beginthread` 和 `CreateThread` 都是用于创建线程的函数,但它们在使用上有一些区别。 `_beginthread` 是C/C++标准中的函数,用于创建一个新的线程。它的原型如下: ```c++ uintptr_t _beginthread(void (__cdecl *start_address)(void*), unsigned stack_size, void* arglist); ``` 其中,`start_address` 是线程函数的地址,`stack_size` 是线程堆栈的大小,`arglist` 是传递给线程函数的参数。`_beginthread` 函数会创建一个新的线程,并在该线程中执行指定的线程函数。 而 `CreateThread` 是Windows API中的函数,用于创建一个新的线程。它的原型如下: ```c++ HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); ``` 其中,`lpThreadAttributes` 是线程的安全属性,`dwStackSize` 是线程堆栈的大小,`lpStartAddress` 是线程函数的地址,`lpParameter` 是传递给线程函数的参数,`dwCreationFlags` 是线程创建的标志,`lpThreadId` 是用于接收新线程ID的指针。`CreateThread` 函数会创建一个新的线程,并在该线程中执行指定的线程函数。 两者的区别主要在于: - `_beginthread` 是C/C++标准中的函数,而 `CreateThread` 是Windows API中的函数。 - `_beginthread` 创建的线程会自动终止,而 `CreateThread` 创建的线程需要手动调用 `ExitThread` 函数来终止。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值