• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 310
  • Last Modified:

Catching the pointers of worker threads

Hello Friends,


To kill the threads I am using following code idea in my application. After killing the threads also, I am seeing some of the threads are still running in my application

CObArray threadArray;

UINT ExecThread(LPVOID lp)
{
     int i=0,sum=0;
     Sleep(10000);
     for(i=0;i<1000;i++)
          sum+=i;

     CString str_sum;
     str_sum.Format ("%d",sum);
     AfxMessageBox("The sum is "+str_sum);
     return 0;    

}

void CTestKillThreadDlg::OnButton1()
{
     // TODO: Add your control notification handler code here

     
     array.Add(AfxBeginThread(ExecThread,NULL,THREAD_PRIORITY_NORMAL+1));
}

void CTestKillThreadDlg::OnButton2()
{
     // TODO: Add your control notification handler code here
         try
        {
     CWinThread* thread=(CWinThread*)array.GetAt(0);
     TerminateThread (thread->m_hThread ,0);
 array.RemoveAt(0);
        }catch(...)
        {
                      array.RemoveAt(0);
                           //  I put catch block here bcause, if  a thread that i am accessing here is already executed, then
                          //  TerminateThread (thread->m_hThread ,0); is raising exception, hence treating it as executed i am
                          //  removing that thread from array

         }

}


what is the problem in my codes??

Ad also I need to catch the pointers of all worker threads that are still in memory


thanks
sudhakar
0
sudhakar_koundinya
Asked:
sudhakar_koundinya
2 Solutions
 
AlexFMCommented:
Using TerminateThread is wrong practice and should be used only for threads which are not responding. Thread should exit by natural way by returning from the thread function. I described this in one of your previous questions.
Exception is raised because CWinThread object created by AfxBeginThread has m_bAutoDelete member TRUE, and CWinThread object deletes itself. To prevent this, create thread in suspended state, change m_bAutoDelete to FALSE and resume thread.
I don't see full code in your post - where is loop which enumerates all worker threads?
Maybe OnButton1 runs one thread, and OnButton2 kills first thread in array? So, you click once on button1 and once on button2, and see that one thread is still running. Maybe this is main application thread?
0
 
SteHCommented:
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now