A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.[1]
AfxBeginThread 是由 MFC 提供,header 是 afxwin.h。要 end thread,可在主函数内调 AfxEndThread 或直接从 thread 主函数返回。注意不要在一个 MFC 程序中使用 _beginthreadex 或者 CreateThread 来创建 thread。通过阅读该函数的源码不难理解原因。它首先创建了相应的 CWinThread 对象,然后调用 CWinThread::CreateThread 来创建 thread。而 CWinThread::CreateThread 函数一开始就做了很多 MFC 特有的 thread 初始化的操作,比如创建了两个 event 内核对象;然后通过 _beginthreadex 创建 thread。如果在 MFC 程序中,用 MFC 来创建 thread,又用 CRT 或者 Windows API 对 thread,就会出现控制混乱的局面,从而导致一些无法预料的错误。 总结一下:对于 thread 的主函数,如果会调用 CRT 的函数,则必须确保会成对使用 _beginthreadex/_endthreadex; 如果会调用 MFC 的函数,则必须确保会成对使用 AfxBeginThread/ AfxEndThread;如果都没有,才可以使用 CreateThread/ExitThread。一个大致的从顶层到底层的逻辑包含关系是,AfxBeginThread 包含 _beginthreadex; _beginthread 是 _beginthreadex 的功能子集(详细区别在 threadex.c 文件中),但二者都是 CRT 层面;_beginthread 和 _beginthreadex 又包含 CreateThread。
References: