Thread: Memory deallocation problem

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    205

    Memory deallocation problem

    Hi,
    I have a thread that contains pointers in them. I use CreateThread(...) to create and launch the thread and TerminateThread() to kill it. The pointers are set up as follows:
    Code:
    CVideo* pThis = (CVideo*)pSimulatorDlg;
    CWnd* pLabel = pThis->theTab->GetDlgItem(IDC_FREE_LABEL);
    CProgressCtrl* pProgress = (CProgressCtrl*)pThis->theTab->GetDlgItem(IDC_FREE_PROGRESS);
    CWnd* pStats = pThis->theTab->GetDlgItem(IDC_FREE_STATS);
    My question is can those pointers cause memory leakage when the program exits and should I have done something special before killing the thread. Thank you
    Amish

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    No these are handles of allready existing objects.
    BTW It is better to just return from your main thread function or call ExitThread(), TerminateThread is only suposed to be used in certain cercumstances.

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    205
    Quote Originally Posted by Quantum1024
    No these are handles of allready existing objects.
    BTW It is better to just return from your main thread function or call ExitThread(), TerminateThread is only suposed to be used in certain cercumstances.
    Yes I know but ExitThread() can only be used inside the thread. I need to kill the thread from outside.
    I also cannot set a while loop waiting for a certain variable to change and fall through and exit the thread because there are multiple instances of that thread running around and any variable would have to be static. Any change in that static variable will affect all the threads instead of just one.

    Do you think because I call TerminateThread it would cause the memory leaks. I can post the whole function if it may be helpful.
    Thanks a lot,
    Amish

  4. #4
    Registered /usr
    Join Date
    Aug 2001
    Location
    Newport, South Wales, UK
    Posts
    1,273
    If you need to kill the thread from outside, then signal the thread that you want it to end rather that terminate it. For example, you could have a global variable and check inside the thread to see if it's nonzero. If it is, exit. e.g.
    Code:
    int g_iKill = 0;   // global
    
    void Thread(void)   // your thread
    {
       if (g_iKill)
          return;
    
    }

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    Quote Originally Posted by axr0284
    Do you think because I call TerminateThread it would cause the memory leaks.
    Amish
    Yes TerminateThread dosen't give the thread any chance to clean up.
    If you want to use the Global Variable option you could have an array of variables the size of the maxinum number of threads your program will use.
    Another option is to use thread Messages.
    in your thread check to see if a quit message has been received.
    Code:
    MSG Msg;
    if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)
    {
       if (Msg.message==WM_QUIT)
          return 0;
    }
    And from your main Thread
    Code:
    PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
    I didn't test that but it should work.
    Another common cause of memory leaks in multithreaded applications is forgetting to call CloseHandle on the Thread handle. You should call CloseHandle on every thread handle when you don't need to use it anymore, doing so will not terminate your thread.
    Last edited by Quantum1024; 03-17-2005 at 05:23 AM.

  6. #6
    Registered User
    Join Date
    Dec 2004
    Posts
    205
    Thanks Quantum1024,
    that was some helpful piece of info. It works if I want to kill the thread while the program is still running. But if a user clicks on the Exit button "X", I would like my program to make sure the thread returns before the program exits.(If I don't it gives me memory leaks again) I tried putting a while loop right after I use PostThreadMessage() as shown below:
    Code:
    if(m_hProgressThread != NULL && !PostThreadMessage(m_connectThreadID, WM_QUIT, 0, 0)) {		
    			AfxMessageBox("Progress thread could not be terminated");
    	}
    	
    while(!threadEnded) {
         ::Sleep(1000);
    }
    
    	threadEnded = true;
    	CloseHandle(m_hProgressThread); // Reset the progress bar thread handle
    	m_hProgressThread = NULL;
    	m_connectThreadID = 0;
    The while loop waits on threadEnded which gets set by the thread just before it does return 0; as shown below:
    Code:
    DWORD WINAPI CVideo::VideoFreeSpaceThreadHandler(LPVOID pSimulatorDlg) 
    {
    	
     pThis->threadEnded = false; // Used to notify the outside that this thread ended.
    	
    while(!exitThisThread) {
    	
    	MSG Msg;
    		if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE))
    		{
    			if (Msg.message==WM_QUIT) {
    				exitThisThread = true;	
    			}
    		}
    
    		DO SOMETHING USEFUL
    	
    		Sleep(1000); // Make the thread sleep for 1 second before repeating
    	}
    	pThis->threadEnded = true;
    	return 0;
    }
    Alas the program hangs when I do that. Is there a more efficient way of doing this. Thank you for any help you can provide
    Amish

  7. #7
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    A message loop is a big overkill just for telling your thread to exit. If your thread actaully needed a message loop, then it would make sense.

    You can use InterlockedExchange() on a volatile global variable as SMurf [kinda] suggested. Or you can use a synchronization object and one of the wait functions to signal the thread to exit.

    To determine if and when a thread exits, use one of the wait functions on the threads handle.

    Also, here's a thread wrapper clas you may be interested in.
    http://cboard.cprogramming.com/showthread.php?t=59695

    gg

  8. #8
    Registered User
    Join Date
    Feb 2002
    Posts
    329
    You also could use a flag for each thread;
    Code:
    // Program mainthread
    long lThreadCnt=0;
    // Start threads
    datastruct.lFlag=0;
    lThreadCnt++;
    datastruct.bStored=false;
    datastruct.lFlag |= lThreadCnt;
    BeginThread()
    while(!datastruct.bStored)
      Sleep(10);
    lThreadCnt++;
    datastruct.bStored=false;
    datastruct.lFlag |= lThreadCnt;
    BeginThread()
    while(!datastruct.bStored)
      Sleep(10);
    //etc...
    // Store lThreadCnt to a local variable inside the thread
    // Send datastruct to thread as parameter
    
    // WM_DESTROY
    datastruct.lFlag=0
    // Wait for termination of threads
    // inside each thread
    Code:
    long lThreadId=lThreadCnt from mainthread;
    datastruct.bStored=true;
    while((datastruct->lFlag & lThreadId)==lThreadId){
      //Do something
      Sleep(some time)?
    }
    Last edited by knutso; 03-18-2005 at 04:06 AM.

  9. #9
    Registered User
    Join Date
    Dec 2004
    Posts
    205
    Thanks for the help, I will try out all these options. Hopefully it should solve my problem.
    Amish

  10. #10
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    knutso - that is improper synchronization. Read my posts in the following thread for an explanation with lots of links to read up on.

    http://cboard.cprogramming.com/showthread.php?t=59236

    gg

  11. #11
    Registered User
    Join Date
    Feb 2002
    Posts
    329
    You live, you learn...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with linked list and shared memory
    By Sirfabius in forum C Programming
    Replies: 10
    Last Post: 11-10-2008, 04:45 PM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  4. my C++ program hangs during memory deallocation.
    By the-tzar in forum C++ Programming
    Replies: 6
    Last Post: 03-06-2004, 10:39 AM
  5. Memory Problem - I think...
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 10-24-2001, 12:14 PM