要不要调用_endthreadex

hxyman 2009-06-01 12:17:50
http://msdn.microsoft.com/en-us/library/kdzttdcb(VS.80).aspx

You can call _endthread or _endthreadex explicitly to terminate a thread; however, _endthread or _endthreadex is called automatically when the thread returns from the routine passed as a parameter. Terminating a thread with a call to endthread or _endthreadex helps to ensure proper recovery of resources allocated for the thread.

这里说函数返回时会自动调用,但是后面举的例子里全部手动调用了 _endthreadex

....
unsigned Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n" );

while ( Counter < 1000000 )
Counter++;

_endthreadex( 0 );
return 0;
}
....

WHY???
...全文
161 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hxyman 2009-06-01
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dch4890164 的回复:]
return 0;
跟踪一下,这句能否被执行
如果不能被执行,就说明本来操作系统要做的事情让你给做了,资源立刻就被回收了
而操作系统不会再次调用_endthreadex
只是一种猜想,还没有研究这么深
[/Quote]

如你所说,_endthreadex后面的没有执行。明白了。谢谢楼上各位。

附测试代码(MFC)
---------------------------
unsigned Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
::AfxMessageBox( "In second thread...\n" );

while ( Counter < 1000000 )
Counter++;

_endthreadex( 0 );
::AfxMessageBox("After _endthreadex( 0 )");
return 0;
};

void CtestendDlg::OnBnClickedOk()
{
//OnOK();
HANDLE hThread;
unsigned threadID;

::AfxMessageBox( "Creating second thread...\n" );

// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );

// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject( hThread, INFINITE );
::AfxMessageBox( "Counter should be 1000000; it is-> %d\n", Counter );
// Destroy the thread object.
CloseHandle( hThread );

}
dch4890164 2009-06-01
  • 打赏
  • 举报
回复
return 0;
跟踪一下,这句能否被执行
如果不能被执行,就说明本来操作系统要做的事情让你给做了,资源立刻就被回收了
而操作系统不会再次调用_endthreadex
只是一种猜想,还没有研究这么深
bdzwj 2009-06-01
  • 打赏
  • 举报
回复
不用
  • 打赏
  • 举报
回复
那就调用2次了.
dong364 2009-06-01
  • 打赏
  • 举报
回复
建议让线程自然结束, 不需要调用_endthreadex( nRet );

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧