VC++ MSDN中的 _beginthreadex与_endthreadex 的使用例子

转自
http://blog.csdn.net/pacewalker/article/details/6947123

1._beginthread, _beginthreadex .
用于创建线程

uintptr_t _beginthread( 
   void( *start_address )( void * ),
   unsigned stack_size,
   void *arglist 
);
uintptr_t _beginthreadex( //推荐使用
   void *security, //安全属性,NULL为默认安全属性
   unsigned stack_size, //指定线程堆栈的大小。如果为0,则线程堆栈大小和创建它的线程的相同。一般用0
   unsigned ( *start_address )( void * ), //指定线程函数的地址,也就是线程调用执行的函数地址(用函数名称即可,函数名称就表示地址)
   void *arglist, //传给线程的参数指针;传多个参数时请用结构体 //可以通过传入对象的指针,在线程函数中再转化为对应类的指针
   unsigned initflag, //线程初始状态,0:立即运行;CREATE_SUSPEND:suspended(悬挂)
   unsigned *thrdaddr //用于记录线程ID的地址
);


参数:
start_address
Start address of a routine that begins execution of a new thread. For _beginthread, the calling convention is either __cdecl or __clrcall; for _beginthreadex, it is either__stdcall or __clrcall.
对于_beginthread,调用约定 是__cdecl或__clrcall; 对于_beginthreadex,则是either__stdcall或__clrcall。
stack_size
Stack size for a new thread or 0.
arglist
Argument list to be passed to a new thread or NULL.
security
Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If NULL, the handle cannot be inherited. Must be NULL for Windows 95 applications.
initflag
Initial state of a new thread (0 for running or CREATE_SUSPENDED for suspended); use ResumeThread to execute the thread.
thrdaddr
Points to a 32-bit variable that receives the thread identifier. Might be NULL, in which case it is not used.

2._endthread, _endthreadex
用于关闭各个使用_beginthread or _beginthreadex创建的线程

void _endthread( void );
void _endthreadex( //推荐使用
   unsigned retval 
);



例子:

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


输出:

Creating second thread...
In second thread...
Counter should be 1000000; it is-> 1000000


一些比较具体的例子:
http://hi.baidu.com/qinpc/blog/item/5aaa8b54918e541b3a2935ee.html
http://www.cppblog.com/mzty/archive/2007/07/25/28756.html

你可能感兴趣的:(VC++ MSDN中的 _beginthreadex与_endthreadex 的使用例子)