Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Killing a Thread

Status
Not open for further replies.

faisiaf

Programmer
Nov 16, 2002
3
US
How to kill a thread by using the thread id?

I have created 2 threads using CreateThread Method

I want to kill one thread from another by passing the thread ID.

What is the API for the same.

Warm Regards
Faisal
 
The best way is to get the thread you wish to 'kill' to exit. You can do this by either posting a message to the thread (assuming you've got a message loop in the thread) or by using an event/semaphore to indicate to the thread that it can die.

The other way is to call TerminateThread on the thread handle.

The difference? Method 1 will allow the thread to release any resources etc (including any 'C' runtime clearup), Method 2 will pull the plug and not allow any clearup. Our experience is to use method 1 if at all possible and only resort to method 2 if all else fails.

By the way, if you're using ANY 'C' runtime calls, you must use beginthread/endthread rather than CreateThread/ExitThread; failure to do so results in small memory leaks.
 
Temps,

Good post, and actually it can get worse that that. Something about 'C' runtime calls locking up if the right sequence occurs. This might even be tied into beginthread vs. CreateThread and TerminateThread etc.

If your using MFC you will never know when a 'C' runtime might be used so pretty much don't use CreateThread and you might as well just exit your process as use TerminateThread.

There are several articles on MSDN about this which should be read instead of using the information I provided here.

-pete
 
Yeah Faisal, I think both of these gentlemen are right.Best way is usage of TerminateThread...
 
Using TerminateThread may cause problems of resources not being freed. To overcome this, please look at thread116-348254 Marcel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top