天天看点

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