Windows threading: _beginthread vs _beginthreadex vs CreateThread C++

后端 未结 17 1465
臣服心动
臣服心动 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:50

    You should use _beginthread or _beginthreadex to allow the C runtime library to do it's own initialization of the thread. Only C/C++ programmers need to know this as they should now the rules of using their own development environment.

    If you use _beginthread you do not need to call CloseHandle as the RTL will do for you. This is why you cannot wait on the handle if you have used _beginthread. Also _beginthread leads to confusion if the thread function exits immediately (quickly) as the launching thread my be left holding an invalid thread handle to the thread it just launched.

    _beginthreadex handles can be used for wait but also require an explicit call to CloseHandle. This is part of what makes them safe for using with wait. There other issue to make it completely foolproof is to always start the thread suspended. Check for success, record handle etc. The resume thread. This is required to prevent a thread from terminating before the launching thread can record its handle.

    Best practice is to use _beginthreadex, start suspended then resume after recording handle, wait on handle is OK, CloseHandle must be called.

提交回复
热议问题