当你创建工作线程CWinThread *pSndTread = AfxBeginThread(fun,param);
如果你设置 pSndTread->m_bAutoDelete = FALSE;则需要你在线程结束后,要手动delete 掉 pSndTread对象;
如果你不设置m_bAutoDelete的话,则需要保证线程中始终在任何情况下都能执行 return 0;语句返回,因为这样不但可以将在线程中使用return返回所有资源都可以得到释放,包括c++对象。
这是我在工作中遇到的问题:我通过一个菜单选项start来开启 、stop来停止 我的发送和接收线程,它们通过一个公用变量m_bStart来控制是否终止线程的运行,但是不可避免的有这样的情况产生:我只点击的start选项来创建并开启线程,在没有点击stop按钮的情况下,通过关闭按钮来终止程序 的运行,此时就会产生线程的资源没有完全回收就退出的情况,memory leaks 就产生了:output:
Detected memory leaks!
Dumping objects ->
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {747} client block at 0x01099E38, subtype c0, 68 bytes long.
a CWinThread object at $01099E38, 68 bytes long
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {741} client block at 0x01099BE8, subtype c0, 68 bytes long.
a CWinThread object at $01099BE8, 68 bytes long
Object dump complete.
Dumping objects ->
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {747} client block at 0x01099E38, subtype c0, 68 bytes long.
a CWinThread object at $01099E38, 68 bytes long
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {741} client block at 0x01099BE8, subtype c0, 68 bytes long.
a CWinThread object at $01099BE8, 68 bytes long
Object dump complete.
这时,我们需要处理这种异常情况:
设置全局的CEvent RecStopEvent;
在OnClose函数中,
RecStopEvent.SetEvent();
SndStopEvent.SetEvent();
RecStopEvent.Unlock();
SndStopEvent.Unlock();
SndStopEvent.SetEvent();
RecStopEvent.Unlock();
SndStopEvent.Unlock();
CDialogEx::OnClose();
在线程函数中:
while( TRUE )
{
if( WAIT_OBJECT_0 == WaitForSingleObject(SndStopEvent, 200)) // 收到激发态的消息
{
return 0;//正常退出
}
{
if( WAIT_OBJECT_0 == WaitForSingleObject(SndStopEvent, 200)) // 收到激发态的消息
{
return 0;//正常退出
}
...
}
WaitForSingleObject函数
VC声明编辑本段说明
DWORD WINAPI WaitForSingleObject(参数
hHandle [in]对象句柄。可以指定一系列的对象,如Event、Job、Memory resource notification、Mutex、Process、Semaphore、Thread、Waitable timer等。返回值
执行成功,返回值指示出引发函数返回的事件。它可能为以下值:WAIT_ABANDONED0x00000080L | The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread and the mutex state is set to nonsignaled. If the mutex was protecting persistent state information, you should check it for consistency. |
WAIT_OBJECT_00x00000000L | The state of the specified object is signaled. |
WAIT_TIMEOUT0x00000102L | The time-out interval elapsed, and the object's state is nonsignaled. |
WAIT_FAILED(DWORD)0xFFFFFFFF | The function has failed. To get extended error information, call GetLastError. |