Windows threading: _beginthread vs _beginthreadex vs CreateThread C++

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

    CreateThread() is the straight system call. It's implemented on Kernel32.dll which, most probably, your application will already be linked against for other reasons. It is always available in modern Windows systems.

    _beginthread() and _beginthreadex() are wrapper functions in the Microsoft C Runtime (msvcrt.dll). The differences between the two calls are stated in the documentation. It is thus available when the Microsoft C Runtime is available, or if your application is linked statically against it. You'll likely be linking against that library, too, unless you're coding in pure Windows API (as I personally often do).

    Your question is a coherent and actually a recurrent one. As many APIs, there are duplicate and ambiguous functionality in the Windows API we have to deal with. Worst of all, the documentation does not clarify the issue. I suppose that the _beginthread() family of functions was created for better integration with other standard C functionalities, such as the manipulation of errno. _beginthread() thus integrates better with the C runtime.

    Despite that, unless you have good reasons for using _beginthread() or _beginthreadex(), you should use CreateThread(), mostly because you might get one less library dependency in your final executable (and for MS CRT this does matter a bit). You also have no wrapping code around the call, although this effect is negligible. In other words, I believe that the main reason for sticking with CreateThread() is that there is no good reason to use _beginthreadex() to begin with. The functionalities are precisely, or almost, the same.

    One good reason to use _beginthread() would be (as it seems to be false) that C++ objects would be properly unwinded/destroyed if _endthread() was called.

提交回复
热议问题