天天看點

Windows多線程程式設計--建立線程_beginthreadex

函數原型

uintptr_t _beginthreadex( // NATIVE CODE 
 void *security, 
 unsigned stack_size, 
 unsigned ( __stdcall *start_address )( void * ), 
 void *arglist, 
 unsigned initflag, 
 unsigned *thrdaddr 
 );
           

參數說明

security–線程安全屬性,如果為NULL則為預設安全屬性;

stack_size–線程堆棧的大小,如果為0則表示與建立該線程的線程的堆棧大小相

同,一般設定為0;

start_address–線程函數位址,也即新建立線程入口函數的位址;

arglist–傳遞給線程函數的參數清單,一般為自定義的結構體;

initflag–新線程初始建立時的狀态标志,0表示建立後立即執行,

CREATE_SUSPENDED表示建立後處于挂起狀态,需要調用ResumeThread喚醒線

程然後執行;

thrdaddr–指向接收線程辨別符的32位變量。如果為空,則不使用;

傳回值

If successful, each of these functions returns a handle to the newly created thread; however, if the newly created thread exits too quickly, _beginthread might not return a valid handle. On an error, _beginthread returns -1L, and errno is set to EAGAIN if there are too many threads, to EINVAL if the argument is invalid or the stack size is incorrect, or to EACCES if there are insufficient resources (such as memory). On an error, _beginthreadex returns 0, and errno and _doserrno are set.(如果建立成功則傳回新建立線程的句柄,建立失敗的話傳回0)。

說明

在C/C++語言中我們應該盡量使用_beginthreadex()來代替使用CreateThread(),因

為它比CreateThread()更安全。CreateThread()函數是Windows提供的API接口。

You can call _endthreadex explicitly to terminate a thread; however, _endthreadex

is called automatically when the thread returns from the routine that’s passed as a

parameter. Terminating a thread with a call to _endthread or _endthreadex helps

ensure correct recovery of resources that are allocated for the thread.(您可以顯式

調用_endthreadex終止線程。 但是,當線程從作為參數傳遞的例程傳回時,會自動

調用_endthreadex。 通過調用_endthreadex終止線程有助于確定正确恢複配置設定給該

線程的資源。)

示例代碼

#include "stdafx.h"
#include<windows.h>
#include<process.h>
#include <iostream>
using namespace std;

struct _threadData
{
 int tid;
 char* tname;
};

unsigned int threadFun(LPVOID lpParam)
{
	_threadData *tdata = (_threadData*)lpParam;
	if(tdata == NULL)
	{
		return -1;
	}
	
	//unsigned int tid = GetCurrentThreadId();
 	unsigned int tid = tdata->tid;
 	char *name = tdata->tname;
 	printf("線程ID為 %d 的名稱是: %s\n", tid,name);
 	return 0;
 }

int _tmain(int argc, _TCHAR* argv[])
{
	const int threadNum = 10;
	for(int i = 0; i < threadNum; i++)
	{
		_threadData tData;
		tData.tid = i;
		char str[256];
		sprintf_s(str,256,"Name_%d",i);
		tData.tName = str;

		_beginthreadex(NULL,0,threadFun,(LPVOID)&tData,0,NULL);
		Sleep(10);
	}

	WaitForMultipleObjects();
	getchar();//等待輸入,一直顯示cmd視窗

	return 0;
}

  
           

運作結果

Windows多線程程式設計--建立線程_beginthreadex