CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2001
    Location
    Turkey
    Posts
    173

    thread exit & memory

    I have a UI thread(CMyTHread) derived from CWinThread.


    CMyThread* m_pThread; //member of CTestDialog;

    CTestDialog::OnNewJob()
    {
    ...
    if( NULL != m_pThread )
    {
    m_pThread = new CMyThread( ...some params... );
    m_pThread->CreateThread();
    }
    else
    {
    //it is already doing a job. it is not finished.
    }
    ...
    }


    //thread has finished its job
    //and mimic us about that by posting a win_msg
    // then went out 'IniInstance' method
    //so we are here
    CTestDialog::OnThreadFinished()
    {
    delete m_pThread;
    m_pThread = NULL;
    }

    My question is that:
    Does 'delete m_pThread;' exit the thread and clear the whole memory successfully?

    I ask this question because I noticed that
    CMyThread::ExitInstance() method never called after delete line.
    (CMyThread destructor is virtual)

    *Please note that; I never called AfxEndThread() and PostQuitMessage() in the boundary of CMyThread class!

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    Yes, you are right that the thread doesn't exit when you delete m_pThread. The proper way of terminating your thread is to quit from the loop where your thread is running, i.e. CMyThread::Run().

    An easy way is to check a killed flag while looping. This flag can be set via member function.

    Code:
    CMyThread::Run()
    {
        while( !m_bKill )
        {
            // Perform your task
            ...
        }
    }
    
    CMyThread::Kill()
    {
        m_bKill = TRUE;
    }

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