0

I want to use _beginthreadex and pass a character string, the name of a domain. What is the proper way/best practice to pass it?

  1. By variable itself (sDomain)?
    WCHAR sDomain[256] = {0};
    //...copy domain into sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, sDomain, 0, &threadID);
  1. Or by the address of the variable (&sDomain)?
    WCHAR sDomain[256] = {0};
    //...copy domain into sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, &sDomain, 0, &threadID);
  1. Or do I make a struct and pass the struct element (&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);
JeffR
  • 765
  • 2
  • 8
  • 23
  • 1
    None of the above. sDomain is a local variable of the function, it disappears when the function completes. Typically before the thread starts running, it will inevitably read random garbage. One basic way is to allocate it on the heap (new[] or malloc) and release it in the thread. Or you need to interlock, block on an event that is signaled by the thread function. – Hans Passant Jan 08 '20 at 14:40
  • Good catch. Assume I wait for the thread to exit before continuing the function so it does not disappear, which is the proper way to pass the domain name to the thread? – JeffR Jan 08 '20 at 14:43
  • If you wait for it to exit then there's no point in using a thread at all, you might as well call the thread function directly. – Hans Passant Jan 08 '20 at 14:44
  • True, but this is a microcosm of a bigger code picture, and I'm just looking for the way to properly pass the variable containing the domain to the thread using `_beginthreadex` – JeffR Jan 08 '20 at 14:50
  • 1
    Why don't you use `std::thread`? – Maxim Egorushkin Jan 08 '20 at 15:58
  • 1
    So, assuming you don't want to use a simple function as @HansPassant has said, and because sDomain is an array, you can pass `sDomain` directly. It is the first element array memory address. – SuperG280 Jan 09 '20 at 07:52
  • Maxim, example? – JeffR Jan 13 '20 at 05:54

1 Answers1

1

The following is the simplest code to implement, of course you can customize some type to pass, because the thread function argument type is void, you can do any conversion

#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;
}
Community
  • 1
  • 1
superman
  • 48
  • 3