_beginthreadex()产生的线程return后不能正常退出
我用_beginthreadex()创建一个线程,这个线程是我命令模式中专门处理命令对象的,在程序退出时,我设置它的推出条件为真,并且调试跟踪发现已经执行过return 0了,可是我的主线程用WaitForSignalObjece却不能返回。
我多次跟踪命令处理线程,发现return0后,被阻塞在vc运行库里了。
具体位置是:_endthreadex->ExiteThread()
extern "C" _CRTIMP void __cdecl _free_dbg(
void * pUserData,
int nBlockUse
)
{
/* lock the heap
*/
_mlock(_HEAP_LOCK);
__try {
/* allocate the block
*/
_free_dbg_nolock(pUserData, nBlockUse);
}
__finally {
/* unlock the heap
*/
_munlock(_HEAP_LOCK);
}
}
// this is a static function, it was blocked after returning ;
int egCmdHandleThread::thread_function()
{
while ( !_bRequest2Quit )
{
_semaphore.lock();
handlePendingCommand();
}
return 0;
}
void egCommandHandler::handlePendingCommand( void )
{
while( _commands.size() > 0 )
{
utility::auto_locklockTmp( &_lockCmds);
command_aptr pCommand( _commands.front() );
_commands.pop_front();
pCommand->Execute();
}
}
[解决办法]
很可能的原因的解决方法:
把你的函数声明改为 _stdcall(WINAPI)的
_beginthreadex 调用的函数不应该是_cdecl的
而vc编译器默认的就是_cdecl的
[解决办法]
int egCmdHandleThread::thread_function()
{
while ( !_bRequest2Quit )
{
_semaphore.lock();
handlePendingCommand();
}
return 0;
}
_semaphore.lock();
没有unlock?是不是死锁了?