+ Reply to Thread
Results 1 to 2 of 2

Thread: How to terminate a thread safely in MFC?

  1. #1

    How to terminate a thread safely in MFC?

    Below is the code where I start a thread with a thread function.

    Code:
    UINT ThreadFunc(LPVOID lpVoid)
    {
    	while(true)
    	{
    		//do work here...
    	}
    	
    	AfxEndThread(0, TRUE) ;
    
    	return 0 ;
    }
    void CMyDlg::StartThread()
    {
    	AfxBeginThread((AFX_THREADPROC) ThreadFunc, NULL) ;
    }
    Thread function does work infinitely.

    How can I terminate thread safely from my dialog?

    Please help.

  2. #2
    Junior Member
    Join Date
    May 2012
    Posts
    29
    For you it is simple to do this:

    Code:
    UINT YouThreadFunc(LPVOID lpParam)
    {
         BOOL bIsContinue = (BOOL) lpParam ;
    
         while(bIsContinue)
         {
                //do your work....
         }
         return 0 ;
    }
    
    void CDlg::StopThread()
    {
         bIsContinue = FALSE ;
    }
    You will need to pass the 'bIsContinue' as an argument when you create a thread.

    Whenever you would like to stop the thread, make a call to StopThread() procedure.

    Enjoy!

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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