04030 _beginthreadex _endthreadex 线程 问题
今天一个同事任务单留言,觉得我开启线程后没有END,有点管杀不管埋的意思。
我倒是觉得代码没有问题,因为以前有看过,现在重新记录一下。
启动
hthread = (HANDLE)_beginthreadex(0, 0, Thread, NULL,
CREATE_SUSPENDED, &threadId);
线程
while (p ->b ==1)
&leftsign;
do();
&rightsign;
psip->b=2;
TRACE("Thread out \\r\\n");
return 0;
关闭
for (int i=0;i<10;i++)
&leftsign;
b=0;
OSSleep(100);
if (b==2)
break;
&rightsign;
if (h!=NULL)
&leftsign;
TerminateThread(h,0);
&rightsign;
b=0;
关于_beginthreadex与_endthreadex的问题
在线程函数中,要不要调用_endthreadex来释放堆中内存空间及ExitThread?
如果调用该函数的话,在线程函数中的局部对象将不能得到正常的析构.如果不调用这个函数,无法释放与线程相关的_tiddata结构体. 请高手指点.
_beginthreadex会自动调用_endthreadex
最好在线程函数中不要调用_endthreadex()函数,
最安全的方式是让线程函数自然的return,如果在线程函数中调用了_endthreadex函数的话,线程就会在调用_endthreadex函数调用的地方立即退出,不回继续向下执行,导致在线程局部存储空间中的局部对象或者变量的析构函数不会被调用,有可能导致资源的泄漏!
Jeffrey Richter 给出的一些注解:
first, if you call _beginthreadex, you\’ll get back a handle to the thread. At some point, that thread\’s handle must be closed. _endthreadex **doesn\’t** do it. Normally, the thread that called _beginthreadex (possibly the main thread) will call CloseHandle on the newly created thread\’s handle when the thread handle is no longer needed. Second, you only need to use _beginthreadex if your app uses CRT functions. If it doesn\’t, then you can just use CreateThread. Also, you can use CreateThread if only one thread (the main thread) in your app uses the CRT. If newly created threads don\’t use the CRT, you don\’t need _beginthreadex or the multithreaded CRT.
Windows平台的线程同步机制小结 深入浅出Win32多线程程序设计之线程通信 VC中利用多线程技术实现线程之间的通信 Windows 95 下 多 线 程 编 程 技术 及 其 实 现 多线程编程
历史博文
- 福州100个地名由来 - 2009
- VS2008、DDK XP和DDKWizard搭建驱动开发环境 - 2009
- 20071114 xml xlst WML c# 动态 - 2008
- 20070320 GB 输入法 IDM COMODO mcafee - 2007
- iwas2-动态变量名 PHP代码优化 变量的变量 - 2005
- iwas1-mysql/PHP1 - 2005