Windows线程:_初学者与CreateThread C+

Windows线程:_初学者与CreateThread C+

有什么更好的方法来启动一条线索,_beginthread_beginthreadxCreateThread?

我正在试图确定_beginthread_beginthreadexCreateThread..所有这些函数都返回一个新创建的线程句柄,我已经知道CreateThread在发生错误时提供了一些额外的信息(可以通过调用GetLastError).。但是当我使用这些函数时,我应该考虑什么呢?

我正在使用一个windows应用程序,所以跨平台兼容性已经不可能了。

我已经阅读了MSDN文档,我只是不明白,例如,为什么会有人决定使用_start线程而不是CreateThread,反之亦然。

干杯!

更新:好的,谢谢你提供的所有信息,我也在几个我不能打电话的地方读到过WaitForSingleObject()如果我用_beginthread()但如果我打电话_endthread()在线上不应该起作用吗?那是怎么回事?


白板的微信
浏览 335回答 3
3回答

www说

CreateThread()是一个原始的Win 32 API调用,用于在内核级别创建另一个控制线程。_beginthread() & _beginthreadex()是调用C运行时库的调用吗?CreateThread()幕后。一次CreateThread()已经回来了,_beginthread/ex()负责额外的簿记,以使C运行时库在新线程中可用&一致。在C+中,您几乎可以肯定地使用_beginthreadex()除非您根本不链接到C运行时库(也就是MSVCRT*.dll/.lib)。

子衿沉夜

有几个不同之处_beginthread()和_beginthreadex(). _beginthreadex()是为了表现得更像CreateThread()(这两个参数以及它的行为方式)。如果您使用的是C/C+运行时,则必须使用_beginthread()/_beginthreadex()而不是CreateThread()这样,运行时就有机会执行自己的线程初始化(设置线程本地存储,等等)。实际上,这意味着CreateThread()应该不会被你的代码直接使用。的MSDN文档_beginthread()/_beginthreadex()其中一个更重要的是,因为线程句柄是由_beginthread()当线程退出时,CRT自动关闭该线程,“如果_初学者线程生成的线程快速退出,则返回给_初学者线程调用方的句柄可能无效,或者更糟糕的是指向另一个线程”。以下是评论的内容_beginthreadex()在CRT消息来源中必须指出:Differences between _beginthread/_endthread and the "ex" versions: 1)  _beginthreadex takes the 3 extra parameters to CreateThread   which are lacking in _beginthread():     A) security descriptor for the new thread     B) initial thread state (running/asleep)     C) pointer to return ID of newly created thread 2)  The routine passed to _beginthread() must be __cdecl and has   no return code, but the routine passed to _beginthreadex()   must be __stdcall and returns a thread exit code.  _endthread   likewise takes no parameter and calls ExitThread() with a   parameter of zero, but _endthreadex() takes a parameter as   thread exit code. 3)  _endthread implicitly closes the handle to the thread, but   _endthreadex does not! 4)  _beginthread returns -1 for failure, _beginthreadex returns   0 for failure (just like CreateThread).为VS 2012执行的CRT有一个额外的初始化在_beginthreadex()*如果该过程是一个“打包应用程序”(如果从GetCurrentPackageId())运行时将在新创建的线程上初始化MTA。

守着星空守着你

一般来说,正确的做法是打电话给_beginthread()/_endthread()(或ex()变体)。但是,如果使用CRT作为.dll,则CRT状态将被正确初始化,并作为CRT的状态销毁。DllMain将被调用DLL_THREAD_ATTACH和DLL_THREAD_DETACH打电话时CreateThread()和ExitThread()或者分别回来。这个DllMainCRT的代码可以在VC\CRT\src\crtlib.c下的VS安装目录中找到。
打开App,查看更多内容
随时随地看视频慕课网APP