温馨提示×

c++中beginthreadex的用法是什么

c++
小亿
98
2023-11-01 01:23:58
栏目: 编程语言

_beginthreadex 是一个用于创建线程的函数,在C++中使用,其声明如下:

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

参数说明如下:

  • security:一个指向线程安全属性的指针,通常设置为NULL
  • stack_size:以字节为单位指定线程堆栈的大小,默认为0,表示使用默认大小。
  • start_address:线程函数的地址,这个函数会在新线程中被调用。
  • arglist:传递给线程函数的参数。
  • initflag:创建线程的标志,可以是0或CREATE_SUSPENDED。
  • thrdaddr:指向接收线程标识的无符号整数的指针。

_beginthreadex 函数会创建一个新的线程,并返回一个线程句柄。这个线程句柄可以用于操作和管理这个线程,比如等待线程结束、终止线程等。在使用完线程句柄后,需要调用CloseHandle函数释放资源。

一个简单的使用示例:

#include <iostream>
#include <windows.h>
#include <process.h>

unsigned __stdcall MyThread(void* arg)
{
    int* num = (int*)arg;
    std::cout << "This is thread " << *num << std::endl;
    return 0;
}

int main()
{
    HANDLE hThread;
    unsigned threadID;

    int threadArg = 1;
    hThread = (HANDLE)_beginthreadex(NULL, 0, &MyThread, &threadArg, 0, &threadID);

    if (hThread == NULL)
    {
        std::cout << "Failed to create thread" << std::endl;
        return 1;
    }

    // 等待线程结束
    WaitForSingleObject(hThread, INFINITE);

    // 关闭线程句柄
    CloseHandle(hThread);

    return 0;
}

上述示例中,_beginthreadex 函数用于创建一个线程,传递线程函数MyThread的地址和参数threadArg。然后使用返回的线程句柄 hThread 等待线程结束,并在结束后关闭线程句柄。

0