用哪个函数创建线程(AfxBeginThread)

来源:互联网 发布:php源码怎么本地测试 编辑:程序博客网 时间:2024/05/14 14:52
创建线程的函数有CreateThread()、AfxBeginThread()和 _beginthreadex,我们平时使用的时候应该如何选择呢?当然我们要听微软的,微软建议我们不要直接使CreateThread。下面是MSDN的原文:

"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."

意思是如果要使用CTR,就用_beginthreadex 和_endthreadex,不要使用CreateThread 和ExitThread,如果使用 CreateThread ,还在线程中调用了CRT,CRT会在低内存的情况下结束进程。
那为什么会有问题呢?因为C运行时库使用了多个全局变量(例如errno)和静态变量,这可能在多线程程序中引起冲突。假设两个线程都同时设置errno,那后面设置的errno会将先前的覆盖,用户得不到正确的错误信息。

用MFC编程,也不要用CreateThread,最好使用AfxBeginThread,它用数据结构同步机制,解决了上述问题,应该是安全的。
当然如果你用CreateThread也使用了CRT,程序跑得不够久,可能也不会出错.
0 0