1. _beginthreadex/_endthreadex
uintptr_t _beginthreadex (
void *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.
unsigned stack_size, //Stack size for a new thread or 0
unsigned ( *start_address )( void * ), //Start address of a routine that begins execution
//of a new thread. The calling convention is
//__stdcall or __clrcall
void *arglist, //Argument list to be passed to a new thread or NULL
unsigned initflag, //Initial state of a new thread (0 for running or CREATE_SUSPENDED
//for suspended); use ResumeThread to execute the thread
unsigned *thrdaddr //Pointer to address that receives the thread identifier. Might be null
);
创建一个线程.
void _endthreadex( unsigned retval );
与_beginthread相比:
1)、创建的线程可以处于suspended状态,可以指定安全级别,可以通过threadID进行访问。
2)、线程调用的函数必须有返回值
3)、当线程创建失败时,返回0
4)、函数返回的handle可以被用于同步的API。
5)、需要在线程结束后,显示的调用CloseHandle.
示例:
#include <windows.h>
#include <stdio.h>
#include <process.h>
unsigned __stdcall ThreadFunc(void* pArgs ) {
printf( "In second thread...\n" );
_endthreadex( 0 );
return 0;
}
int main() {
HANDLE hThread;
unsigned threadID;
printf( "Creating second thread...\n" ); // Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &ThreadFunc, NULL, 0, &threadID );
WaitForSingleObject( hThread, INFINITE );
// Destroy the thread object.
CloseHandle( hThread );
}
2. CreateThread/ExitThreadHANDLE CreateThread(
SEC_ATTRS securityAttributes,
ULONG stackSize,
SEC_THREAD_START startFunction,
PVOID threadParameter,
ULONG creationFlags,
PULONG threadId
};
创建线程,线程结束后需要调用CloseHandle(主线程),也可以调用ExitThread结束(创建的线程)3. _beginthread/_endthread
uintptr_t _beginthread(
void( *start_address )( void * ), //Start address of a routine that begins execution
//of a new thread. The calling convention is __cdecl
//or __clrcall
unsigned stack_size, //Stack size for a new thread or 0
void *arglist //Argument list to be passed to a new thread or NULL
);
void _endthread( void );
当线程创建失败时,返回-1.
没有_beginthreadex安全。当_beginthread创建的线程被很快的执行完毕。返回的handle有可能会无效,因为_endthread会自动调用CloseHandle。
示例:
volatile bool threadStarted = false;
void leaker()
{
std::cout << atoi( "0" ) << std::endl;
}
void __cdecl beginThreadFunc( LPVOID )
{
leaker();
threadStarted = false;
}
int main()
{
int i;
for(i = 0; i < 50; i++)
{
while( threadStarted )
Sleep( 5 );
threadStarted = true;
_beginthread( beginThreadFunc, 0, 0 );//1
}
return 0;
}
PS:有的网上说CreateThread会导致memleak,在Win32+VS2005sp1下测试没有发现。不知是不是因为线程库已经fix bug过。