美文网首页
2018-05-15

2018-05-15

作者: haoanjing | 来源:发表于2018-05-15 13:48 被阅读0次

关于线程函数结束前显式调用_endthreadex

转载自 http://www.xuebuyuan.com/349166.html

1. 本来,MSDN已经明确指出了:

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 to_beginthread or

_beginthreadex. Terminating a thread with a call toendthread or _endthreadex helps ensure proper recovery of

resources allocated for the thread(http://msdn.microsoft.com/en-us/library/vstudio/hw264s73.aspx).

即,线程从线程函数(例程)返回后,将自动调用_endthreadex. 意即不必在线程函数返回前显式调用_endthreadex.

而在示例_beginthreadex函数时,MSDN给出了如下例子(http://msdn.microsoft.com/en-us/library/kdzttdcb(v=VS.80).aspx):

unsigned Counter; unsigned __stdcall SecondThreadFunc( void* pArguments ){    printf( "In second thread...\n" );    while ( Counter < 1000000 )        Counter++;_endthreadex( 0 );return 0;}

2. 到底要不在线程函数前调用_endthreadex呢?

MSDN在对_endthreadex的注解中提到:

_endthread and _endthreadex cause C++ destructors pending in the thread not to be called.

意即在线程中调用_endthreadex,会导致C++对象的析构函数挂起而不被调用。如果在线程函数中生成的对象关乎资源分配,则可能引起资

源不能被正常回收(destructor不被调用)。

相关资料:

http://stackoverflow.com/questions/9090143/shouldnt-i-use-endthreadex-in-thread-procedure-for-stack-unwinding

http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2005-05/msg00096.html

而如果非要用怎么办?

如下例(http://blog.chinaunix.net/uid-406135-id-3421540.html):

在MSDN的示例中,线程函数结束都有

    _endthreadex( 0 );

    return 0;

以前,我一直不加_endthreadex( 0 ),因为觉得它很丑很冗余,MSDN上如是说:

_endthread or _endthreadex is called automatically when the thread returns from the routine passed as a parameter.

也就是它屁用没有,假如我写成:

_endthreadex( 0 );

    return 1;

还会引起歧义。

今日我一时兴起,在return前加上了 _endthreadex( 0 ),然后就报内存泄露,因为它中止线程前不会析构局部变量。

于是将代码改为:

unsigned __stdcall foo( void* p )

{

    {

        //这里是执行代码

    }

    _endthreadex( 0 );

    return 0;

}

也就是加了个似乎没用的{}。

相关文章

  • 12306

    train.py 最后更新时间:2018-05-15 0:15:23

  • 随想——源于公园、校园、家园

    葱兰朵朵 2018-05-15 17:21 · 字数 1538 · 阅读 1 · 日记本 邀...

  • http理解(中)

    title: http 理解(中)date: 2018-05-15 14:53:22tags: http 确保We...

  • 2018-05-16

    日式 就这么装! 梵客家装青岛公司2018-05-15 日本和式建筑 又称“和样建筑”或...

  • Python递归优化

    博客文章迁移: 2018-05-15 11:17 在codewars上做题时遇到的坑(https://www.co...

  • 日精进打卡(第312天)

    2018-05-15 姓名:李义 公司:........ 组别:259期利他二组 【知~学习】 背诵 六项精进大纲...

  • 2018-05-15

    网海情缘 郝代弟 2018-05-15 17:23 · 字数 1408 · 阅读 0 · 日记本 冥冥之中有...

  • 享受豪华(转录)

    享受豪华(转录) 2018-05-15 10:43:19|分类: 博友芳香 享受豪华 王正方 (作者简介:王正方,...

  • 2018年的电影记录.中

    81. 2018-05-15「杀手乔」Killer Joe,豆瓣评分6.6:被推荐了这个,看完只觉得全片都好病态。...

  • 王霞感恩功课第162

    王霞感恩功课第162天 王霞王夏 2018-05-15 23:26 · 字数 6217 · 阅读 29 · 日记本...

网友评论

      本文标题:2018-05-15

      本文链接:https://www.haomeiwen.com/subject/kquedftx.html