用哪个函数创建线程(AfxBeginThread)
2015-02-03 10:34
369 查看
创建线程的函数有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,程序跑得不够久,可能也不会出错.
"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,程序跑得不够久,可能也不会出错.
相关文章推荐
- CreateThread()线程创建函数,AfxBeginThread等
- CreateThread()线程创建函数,AfxBeginThread等
- 创建一个线程用哪个好?--CreateThread._beginthread.AfxBeginThread比较
- MFC 用afxbeginthread创建线程 线程函数直接 return 0 返回。任务管理器显示线程数与理论值不符
- AfxBeginThread创建线程并指定优先级
- AfxBeginThread函数创建进程
- AfxBeginThread创建用户界面线程
- 在windows上,AfxBeginThread 和 CreateThread 创建的线程是有一点区别的
- _beginthreadex、CreateThread、AfxBeginThread 几个线程函数的区别(转)
- AfxBeginThread创建线程
- mfc下AfxBeginThread创建线程
- 创建线程的方法【CreateThread, AfxBeginThread,_beginthread, _beginthreadex的区别】
- AfxBeginThread函数创建进程
- mfc 创建线程函数AfxBeginThread,线程中访问mfc控件
- AfxBeginThread创建和事件对象结束线程的方法
- AfxBeginThread创建线程并指定优先级
- 用MFC库函数AfxBeginThread()来创建线程
- CreateThread和AfxBeginThread创建线程实例
- [转]创建线程并传递参数--AfxBeginThread
- AfxBeginThread创建线程时出现内存不足