CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 20

Thread: Stop a thread

Threaded View

  1. #1
    Join Date
    Jan 2009
    Posts
    399

    Stop a thread

    Please explain me why the following thread when is forced to stop is not cleaning the heap:
    // here is starting thread
    Code:
    BOOL CMyDoc::ReadHDD(CStringA sVolume)
    {
    	THREADSTRUCT* pTS = new THREADSTRUCT;
    	pTS->m_pDoc = this;
    	pTS->m_sVolume = sVolume;
    	m_pWinThread = AfxBeginThread(&CMyDoc::ReadThread, (LPVOID)pTS, THREAD_PRIORITY_BELOW_NORMAL, CREATE_SUSPENDED, 0, NULL);
    	m_pWinThread->m_bAutoDelete = TRUE;
    	m_pWinThread->ResumeThread();
    
    	return TRUE;
    }
    and
    Code:
    UINT CMyDoc::ReadThread(LPVOID lpParam)
    {
    	THREADSTRUCT* pTS = (THREADSTRUCT*)lpParam;
    
    	if (NULL == pTS)
    		return 0;
    
    
    	//.... code that takes long time, no returning call
    
    	delete pTS;
    
    	return 1;
    }
    where
    Code:
    // inside my CMyDoc header
    
    protected:
    	CWinThread* m_pWinThread;
    
    	struct THREADSTRUCT
    	{
    		CMyDoc* m_pDoc;
    		CStringA m_sVolume;
    	};
    what is happen: if I let that the thread to naturally close it, I mean after the thread is ended and afterwards close my app, everything is ok, I got no memory leak. But if I close my app when the thread is alive (while code that takes long time from the thread is executing), I got memory leak, of course due to pTS object from the heap.

    My question, what is happen when the thread is stopped while that "code that takes long time" is alive ?

    And how to be assured that pTS is properly delete it ?

    P.S.
    Of course, I can live without THREADSTRUCT, it is just for testing and learning purpose.
    P.S.2
    Of course, I can make pTS as CMyDoc member and delete it inside CMyDoc destructor. But I want to understand what happen in this situation.
    Last edited by mesajflaviu; February 17th, 2020 at 06:39 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured