Windows threading: _beginthread vs _beginthreadex vs CreateThread C++

后端 未结 17 1474
臣服心动
臣服心动 2020-11-22 17:26

What\'s a better way to start a thread, _beginthread, _beginthreadx or CreateThread?

I\'m trying to determine what are the adv

17条回答
  •  误落风尘
    2020-11-22 17:34

    Looking at the function signatures, CreateThread is almost identical to _beginthreadex.

    _beginthread, _beginthreadx vs CreateThread

    HANDLE WINAPI CreateThread(
      __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
      __in       SIZE_T dwStackSize,
      __in       LPTHREAD_START_ROUTINE lpStartAddress,
      __in_opt   LPVOID lpParameter,
      __in       DWORD dwCreationFlags,
      __out_opt  LPDWORD lpThreadId
    );
    
    uintptr_t _beginthread( 
       void( *start_address )( void * ),
       unsigned stack_size,
       void *arglist 
    );
    
    uintptr_t _beginthreadex( 
       void *security,
       unsigned stack_size,
       unsigned ( *start_address )( void * ),
       void *arglist,
       unsigned initflag,
       unsigned *thrdaddr 
    );
    

    The remarks on here say _beginthread can use either __cdecl or __clrcall calling convention as start point, and _beginthreadex can use either __stdcall or __clrcall for start point.

    I think any comments people made on memory leaks in CreateThread are over a decade old and should probably be ignored.

    Interestingly, both _beginthread* functions actually call CreateThread under the hood, in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src on my machine.

    // From ~line 180 of beginthreadex.c
    /*
     * Create the new thread using the parameters supplied by the caller.
     */
    if ( (thdl = (uintptr_t)
          CreateThread( (LPSECURITY_ATTRIBUTES)security,
                        stacksize,
                        _threadstartex,
                        (LPVOID)ptd,
                        createflag,
                        (LPDWORD)thrdaddr))
             == (uintptr_t)0 )
    {
            err = GetLastError();
            goto error_return;
    }
    

提交回复
热议问题