Windows多线程编程--创建线程_beginthreadex

_beginthreadex函数用于在C/C++中创建线程,比CreateThread更安全。本文详细介绍了函数参数、返回值及示例代码,展示了如何使用_beginthreadex进行线程管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数原型

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}

  

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值