如何将字符串发送到_beginthreadex 以供线程读取?

How to send a string to _beginthreadex for the thread to read it?

我想使用_beginthreadex 并传递一个字符串,域名。通过它的正确 way/best 做法是什么?

  1. 通过变量本身 (sDomain)?
    WCHAR sDomain[256] = {0};
    //...copy domain into sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, sDomain, 0, &threadID);
  1. 还是通过变量的地址(&sDomain)?
    WCHAR sDomain[256] = {0};
    //...copy domain into sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, &sDomain, 0, &threadID);
  1. 或者我是否创建一个结构并传递结构元素 (&sDomain[0])?
    struct strDomain {TCHAR sDomain[256];};
    strDomain *sDomain = new strDomain[1]();
    //...copy domain into strDomain[0].sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, &sDomain[0], 0, &threadID);

下面是最简单的代码实现,当然你可以自定义一些类型来传递,因为线程函数的参数类型是void,可以任意转换

#include <iostream>
using namespace std;

UINT Thread_SaveDomainName(LPVOID params)
{
    char* szDomain = (char*)params;
    cout<<szDomain<<endl;
    
    return 0;
}

int main()
{
    char* szDomain = "8080";
    UINT threadID = -1;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, (void*)szDomain, 0, &threadID);
    
    return 0;
}