Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Terminating a thread

Terminating a thread

Scheduled Pinned Locked Moved C / C++ / MFC
c++comdesignsysadminperformance
17 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    HomeNuke
    wrote on last edited by
    #1

    I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

    while(1)
    {
    //Code to listen and spawn thread goes here
    }

    However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

    L P E H M 6 Replies Last reply
    0
    • H HomeNuke

      I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

      while(1)
      {
      //Code to listen and spawn thread goes here
      }

      However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Sounds like you're on the right track - just mumbling here... Got a Sleep(...) in you're thread loop? Check for slightly more than STILL_ACTIVE in your shutdown?

          do 
          {
              ::Sleep(100);
              bResult = ::GetExitCodeThread(m\_pMyThread->m\_hThread, &dwExitCode);            
          } while (dwExitCode == STILL\_ACTIVE && bResult);
      

      Do you have an accept socket blocking? Kick it off with a localhost connect. ...end mumble.

      1 Reply Last reply
      0
      • H HomeNuke

        I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

        while(1)
        {
        //Code to listen and spawn thread goes here
        }

        However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

        P Offline
        P Offline
        pba_
        wrote on last edited by
        #3

        Wait for the child thread before leaving the main thread - if you do that in a thread with UI don't forget to pump messages : ....... child thread signal exit ..... //wait for child while( WAIT_OBJECT_0 != ::WaitForSingleObject( hThreadChild, 10)) { MSG msg; while( ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage( &msg); DispatchMessage( &msg); } }

        1 Reply Last reply
        0
        • H HomeNuke

          I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

          while(1)
          {
          //Code to listen and spawn thread goes here
          }

          However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

          E Offline
          E Offline
          Ernest Laurentin
          wrote on last edited by
          #4

          - If your working thread has called accept(socket,..) and is currently waiting for a connection, you may close the socket (closesocket(socket) to force it to return. - In OnClose() function, you need to call closesocket(m_ThreadParam->socket) - You may want to add this new member "socket" in your ThreadParam struct Good luck! - Greatest invention : "The Microchip!"

          1 Reply Last reply
          0
          • H HomeNuke

            I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

            while(1)
            {
            //Code to listen and spawn thread goes here
            }

            However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            "In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success." Why doesn't it work? Most likely your code to check the bool value was not executed because the worker thread was blocking (waiting for other things). There is no way to terminate a worker thread within itself effectively. If you have the thread handle, you can call TerminateThread from outside, but there are warnings against using TerminateThread (see MSDN). User interface thread is different because it has a message pump, so it can process the quit message. But it changes the way your program works.

            1 Reply Last reply
            0
            • H HomeNuke

              I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

              while(1)
              {
              //Code to listen and spawn thread goes here
              }

              However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

              H Offline
              H Offline
              HomeNuke
              wrote on last edited by
              #6

              Thanks to all of you. I will try this when I get home. I just hate when you are running your app in debug mode and as soon as the application stops you get a "Memory leak detected" in your debug window :( Especially since this is a server application I don't want to many memory leaks going on, throught the course of the day it may kill the server, even though at this time the app only generates one thread for the server function, but it generates multiple threads for each connection... Thank you, and I will try all of your suggestions when I get home. However, if anyone has more advice I'm am still open to hearing them. :D HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

              1 Reply Last reply
              0
              • H HomeNuke

                I have been trying to terminate a thread I started in my application. I am writing a server application and have spun a seperate thread off for the server, that in turns spawns another thread when a client connects, and I am using Winsock 2.2. During the listen portion of the server thread I put it in a while loop more specifically:

                while(1)
                {
                //Code to listen and spawn thread goes here
                }

                However, I get a memory leak when I quit the application, since it is in a while loop the thread can not properly terminate. I have tried several methods in order to get it to terminate. Here is what I have tried: In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success. Tried using a loop in the close function to make sure that the thread has stopped by checking the return value of ::GetExitCodeThread and making sure it doesn't return STILL_ACTIVE--No success Current thoughts: Even though this is a worker thread as defined by MFC I'm thinking of turning it into a UI thread so I can use PostQuitMessage and send a user defined message to thread to terminate. Any suggestions to resolving this matter? Thanks in advance for any help. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                M Offline
                M Offline
                Matt Gullett
                wrote on last edited by
                #7

                "In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success." First thing that popped into my head was "is 'Stop' a volatile variable and is it a managed resource? (Do you use a critical section to control who is accessing it? Suggestion: If this is how you want to stop your thread this could work. I would recommend using a short instead of a bool. This way it can have states. Ie. 0=Thread running, 1=Request a stop and 2=Thread stopped. Then you GUI thread can check this before actually closing the window. Second thing that popped into my head is that Stop shold work uness the code you are using in your while loop is blocking and thus never checking Stop. Matt Gullett

                H 1 Reply Last reply
                0
                • M Matt Gullett

                  "In my ThreadParam struct I added a variable bool Stop. When I start the thread I set stop to false and in the while loop I use an if statement to check for Stop. If it is true I break out of the while loop so the thread can close safely. I change Stop to true in the WM_CLOSE message of the MAIN GUI interface--No success." First thing that popped into my head was "is 'Stop' a volatile variable and is it a managed resource? (Do you use a critical section to control who is accessing it? Suggestion: If this is how you want to stop your thread this could work. I would recommend using a short instead of a bool. This way it can have states. Ie. 0=Thread running, 1=Request a stop and 2=Thread stopped. Then you GUI thread can check this before actually closing the window. Second thing that popped into my head is that Stop shold work uness the code you are using in your while loop is blocking and thus never checking Stop. Matt Gullett

                  H Offline
                  H Offline
                  HomeNuke
                  wrote on last edited by
                  #8

                  Just clarifying the acutual code in the while loop now is:

                  listen(sListen, 5);

                  while (1)
                  [
                  if (pThreadData->Stop)
                  break; //Just exit the while loop and let the thread close out
                  ]

                  closesocket(sListen);

                  WSAcleanup();

                  return 0;

                  It is just bare minimum because I'm trying to see why I get the memory leak. I have nothing else in the while loop pertaining to the socket. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                  E L 2 Replies Last reply
                  0
                  • H HomeNuke

                    Just clarifying the acutual code in the while loop now is:

                    listen(sListen, 5);

                    while (1)
                    [
                    if (pThreadData->Stop)
                    break; //Just exit the while loop and let the thread close out
                    ]

                    closesocket(sListen);

                    WSAcleanup();

                    return 0;

                    It is just bare minimum because I'm trying to see why I get the memory leak. I have nothing else in the while loop pertaining to the socket. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                    E Offline
                    E Offline
                    Ernest Laurentin
                    wrote on last edited by
                    #9

                    There's no reason for your thread to block with your example except that your thread is taking up all the CPU. Try putting a Sleep(0) in your loop. Make sure your memory leak is not from "pThreadData" :-O - Greatest invention : "The Microchip!"

                    H 1 Reply Last reply
                    0
                    • E Ernest Laurentin

                      There's no reason for your thread to block with your example except that your thread is taking up all the CPU. Try putting a Sleep(0) in your loop. Make sure your memory leak is not from "pThreadData" :-O - Greatest invention : "The Microchip!"

                      H Offline
                      H Offline
                      HomeNuke
                      wrote on last edited by
                      #10

                      I'll try putting a sleep call in there. I'm hoping that pThreadData is not the leak since I have this pointing to a member variable in the outer class that is defined as my ThreadData struct. I am *assuming* that since the variable is declared on the stack, and space not dynamically allocated, it goes out of scope, and it's memory released, when the class does. Please let me know if this assumption is not correct :) **UPDATE**just thinking about it pThreadData is not the leak because if I remove the while loop there is no memory leak detected. The leak detected is object CWinThread hopefully this additional information is helpful. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                      E 1 Reply Last reply
                      0
                      • H HomeNuke

                        I'll try putting a sleep call in there. I'm hoping that pThreadData is not the leak since I have this pointing to a member variable in the outer class that is defined as my ThreadData struct. I am *assuming* that since the variable is declared on the stack, and space not dynamically allocated, it goes out of scope, and it's memory released, when the class does. Please let me know if this assumption is not correct :) **UPDATE**just thinking about it pThreadData is not the leak because if I remove the while loop there is no memory leak detected. The leak detected is object CWinThread hopefully this additional information is helpful. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                        E Offline
                        E Offline
                        Ernest Laurentin
                        wrote on last edited by
                        #11

                        Fine, I thought you allocate your ThreadData with "new" or malloc... If you are using a CWinThread object, in your case, Set "m_bAutoDelete = TRUE" after starting your thread. By the way, it's not necessary to use CWinThread since what you want is a working Thread. - Greatest invention : "The Microchip!"

                        H 1 Reply Last reply
                        0
                        • E Ernest Laurentin

                          Fine, I thought you allocate your ThreadData with "new" or malloc... If you are using a CWinThread object, in your case, Set "m_bAutoDelete = TRUE" after starting your thread. By the way, it's not necessary to use CWinThread since what you want is a working Thread. - Greatest invention : "The Microchip!"

                          H Offline
                          H Offline
                          HomeNuke
                          wrote on last edited by
                          #12

                          Ah...that could be the step I'm missing :) I'm not inheriting from CWinThread so to speak, but it is what is returned when you call AfxBeginThread() :) I was told not to call CreateThread from within an MFC function or be forewarned about doing so...I don't even know if that is correct now since I have gone through several source codes that utilize MFC and do call CreateThread?!?! Clarification anyone? HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                          E 1 Reply Last reply
                          0
                          • L Lost User

                            Might not get into the while until the listen call returns, i.e. something connects. As stated above, might want to fake a connection on 127.0.0.1 to kick the listen off its perch when shutting down.

                            H Offline
                            H Offline
                            HomeNuke
                            wrote on last edited by
                            #13

                            Checked for that with the debugger was able to start stepping through the while loop. That gave me the impression that I was in there, hopefully the while loop is not split off into it's own thread that runs while listen is tied up :) That would be just my luck... HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                            L 1 Reply Last reply
                            0
                            • H HomeNuke

                              Just clarifying the acutual code in the while loop now is:

                              listen(sListen, 5);

                              while (1)
                              [
                              if (pThreadData->Stop)
                              break; //Just exit the while loop and let the thread close out
                              ]

                              closesocket(sListen);

                              WSAcleanup();

                              return 0;

                              It is just bare minimum because I'm trying to see why I get the memory leak. I have nothing else in the while loop pertaining to the socket. HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #14

                              Might not get into the while until the listen call returns, i.e. something connects. As stated above, might want to fake a connection on 127.0.0.1 to kick the listen off its perch when shutting down.

                              H 1 Reply Last reply
                              0
                              • H HomeNuke

                                Checked for that with the debugger was able to start stepping through the while loop. That gave me the impression that I was in there, hopefully the while loop is not split off into it's own thread that runs while listen is tied up :) That would be just my luck... HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                                L Offline
                                L Offline
                                Lost User
                                wrote on last edited by
                                #15

                                Ok - my impression was that the listen would block until it rec'd a connection. Are you using the WSAAsyncSelect or WSAEventSelect to get around that? Thats different then. Never mind. :)

                                1 Reply Last reply
                                0
                                • H HomeNuke

                                  Ah...that could be the step I'm missing :) I'm not inheriting from CWinThread so to speak, but it is what is returned when you call AfxBeginThread() :) I was told not to call CreateThread from within an MFC function or be forewarned about doing so...I don't even know if that is correct now since I have gone through several source codes that utilize MFC and do call CreateThread?!?! Clarification anyone? HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                                  E Offline
                                  E Offline
                                  Ernest Laurentin
                                  wrote on last edited by
                                  #16

                                  Okay, unless you want to save the returning pointer of CWinThread there's little help to call AfxBeginThread since _beginthreadex is all you need. - Yes, you still can change "m_bAutoDelete" to TRUE - Yes, it's better to call _beginthreadex or _beginthread in MFC but you may still get away with it by calling CreateThread. - Greatest invention : "The Microchip!"

                                  H 1 Reply Last reply
                                  0
                                  • E Ernest Laurentin

                                    Okay, unless you want to save the returning pointer of CWinThread there's little help to call AfxBeginThread since _beginthreadex is all you need. - Yes, you still can change "m_bAutoDelete" to TRUE - Yes, it's better to call _beginthreadex or _beginthread in MFC but you may still get away with it by calling CreateThread. - Greatest invention : "The Microchip!"

                                    H Offline
                                    H Offline
                                    HomeNuke
                                    wrote on last edited by
                                    #17

                                    Ernest thanks for being patient. Yeah all the literature I have on MFC always say use AfxBeginThread, and thanks for elaborating on the different thread calls. I wonder why the PSDK or the many books I HAVE on MFC don't mention those functions?!?! Thanks! HomeNuke ---- "Nuke'd Your Home, Yet?" Run your own PostNuke based web server from home http://www.homenuke.com

                                    1 Reply Last reply
                                    0
                                    Reply
                                    • Reply as topic
                                    Log in to reply
                                    • Oldest to Newest
                                    • Newest to Oldest
                                    • Most Votes


                                    • Login

                                    • Don't have an account? Register

                                    • Login or register to search.
                                    • First post
                                      Last post
                                    0
                                    • Categories
                                    • Recent
                                    • Tags
                                    • Popular
                                    • World
                                    • Users
                                    • Groups