CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 1999
    Posts
    73

    Kill worker thread

    hi all,

    can anyone tell me please, how to kill a worker thread correctly, when closing my app. i have started the thread in CMainFrm.

    please help.... thx...


  2. #2
    Join Date
    Jul 1999
    Location
    India
    Posts
    51

    Re: Kill worker thread

    It is not recommended to "kill" a thread when the application quits. A better and recommended way would be to have a flag (global) in the application that will be switched "on" when the ExitInstance of the application class is entered. All worker threads must keep a watch on this and when this flag comes "on", must relinquish whatever they're doing and end themselves (AfxEndThread). Don't try this function from outside the thread. They must be used within the executing thread to terminate themselves.


    Cheers!
    DP

  3. #3
    Join Date
    May 1999
    Posts
    5

    Re: Kill worker thread

    A better would be to use messages. You can create a message loop in your worker thread function.
    You can assign WM_USER + 1 message that would terminate yor thread.
    You would also assign WM_USER +2 as the message to do your work. In your message loop you can use GetMessage and check for WM_USER +1.When you want to terminate the thread when your main application ends, you can call PostThreadMessage API from your Application's OnDestroy function. You will pass WM_USER+1 in that API.


    .
    .
    void OnDestroy()
    {
    PostThreadMessage(threadid,WM_USER+1,0,0)
    }
    void ThreadFunc()
    {
    MSG msg;
    while(GetMessage(&msg,NULL,0,0))
    {
    if(msg.message== WM_USER+1)
    AfxEndThread(0);
    elseif(msg.message==WM_USER+2)
    // do your work
    else
    {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    }
    }
    }





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