Thread: Exiting a thread from outside the thread ?

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    9

    Exiting a thread from outside the thread ?

    I have the code as follows,

    Code:
    for (;;) {
    
    	if (side == computer)
    	{
    	DWORD Id;
    	HANDLE hThread = CreateThread(0, 0, think, pcon, 0, &Id);
    }
    
    if (input == quit)
    {
    //I want to exit the above thread from outside the thread
    }
    
    }
    So is it possible to exit the thread from outside that thread please?
    Thanks.

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    16
    There are a couple of ways. Most direct is the TerminateThread function. This is basically brute-force kill the thread, no questions asked. Note that this is NOT recommended a number of reasons: for C++ code because the destructors of any classes that were created in the thread will not be called, for code that could be manipulating a DLL (it wouldn't be closed), for code that might have a file or other resource open (it wouldn't be released), etc.

    Another way is to create an event object before you create the thread, give the thread function a pointer to the object, and have the thread check the event periodically (can be done with a while loop) and return when the event signals. Then the parent thread can keep the event object handy and signal it when (in this case) input==quit.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 02-26-2009, 11:48 PM
  2. Terminating secondary thread from another thread
    By wssoh85 in forum C++ Programming
    Replies: 13
    Last Post: 12-19-2008, 05:14 AM
  3. Thread Prog in C language (seg fault)
    By kumars in forum C Programming
    Replies: 22
    Last Post: 10-09-2008, 01:17 PM
  4. pointer to main thread from worker thread?
    By draegon in forum C++ Programming
    Replies: 2
    Last Post: 10-27-2005, 06:35 AM
  5. Critical Sections, destroying
    By Hunter2 in forum Windows Programming
    Replies: 4
    Last Post: 09-02-2003, 10:36 PM