Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

ExitThread, ExitProcess and Closehandle

Posted on 1999-01-25
10
2,273 Views
Last Modified: 2013-12-03
After I use CreateThread(or CreateProcess), which function
should I use to close the Thread(or Process)? CloseHandle or ExitThread(ExitProcess)? Can CloseHandle release the memory of the thread(or Process)? Which one is better?

Also, If the thread(or process) hasn't finished, can I use
closehandle to force it to terminate with memory released?  

I always see examples using CloseHandle, when exitThread or exitprocess be used?

Thanks.
0
Comment
Question by:Torus
  • 5
  • 4
10 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
ID: 1419233
CloseHandle and ExitThread/ExitProcess are unrelated.

You use the ExitXXXX functions to end the code running in a process or thread.  its sort of like the ultimate "return" statement.

Closing a thread handle or process handle does not stop the thread or process from running.  Those handles can be used to monitor a thread/process, or communicate with the thread/process, or in critical conditions, code can use them to terminate a thread or process if other means fail (last ditch atttempt, this should be avoided).  Mostly they are used to monitor the thread/process (to learn when it is done running.)  when your code doesn't need the handle for these purposes it should close it.  It does not matter of the thread or process are running or not at the time the handle is closed.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1419234
>> Also, If the thread(or process) hasn't finished, can I use
>>   closehandle to force it to terminate with memory released?  
No.  But you can use the handled in TerminateThread() and TerminateProcess().  But only in extreme conditions.  If possible let the thread/process terminate when it thinks it is done.  Use this only when the thread/process appears to be locked up or malfunctioning.  

When a process is terminated, most of its memory will be released.  (The memory it used directly will be released, but some memory that the OS might be usig on its behalf, like GUI memory for pens and brushes etc might not get freed.  Since this sort of memory is often very limited, this is a big problem.  That is why these functions should be avoided.)

>>I always see examples using CloseHandle, when exitThread or exitprocess be used?
that seems unusual.  Ussually the thread/process run doesn't ever "see" its own handle, and ussually is not responsible for closing it.  Usually, the code that creates the thread/process has the handle and is responsible for closing that handle--when it no longer wants to monitor ro communicate with the thread/process.
0
 
LVL 86

Expert Comment

by:jkr
ID: 1419235
Hi nietod - you were faster, so i'll add this as a comment...

'CloseHandle()' simply decrements the reference count on the handle object, it should always be used when you no longer need to use the handle.
'ExitProcess()' and 'ExitThread()' can _only_ be used in the _current_ thread/process, i.e. you can't terminate a process different from yours - in this case, 'OpenProcess()' and 'TerminateProcess()' will do the job...
Feel free to ask if you have further questions regarding this issue...
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 2

Author Comment

by:Torus
ID: 1419236
oh! I think I should misconcept on the functions.
BTW, still questions.
I saw a VB examples.

Command1_click( )
    hThread = CreateThread(ByVal 0&, ByVal 0&, AddressOf AsyncFileCopy, ByVal 0&,       ByVal 0&, lpThreadID)
    CloseHandle hThread
end sub

Function AsyncFileCopy() as long
    FileCopy source, destination
end function

It copied a large size of file. In this example, I can't see ExitThread. Should the function
Exithread be added at the end of AsyncFileCopy function?

Moreover, if the Thread is deadlock or whatever reason, it takes a long time to finish,  I need to terminate it. If in this case, using TerminateThread the memory may not be released. Can I use ExitThread outside the function creating the Thread(i.e AsynFileCopy from the above example) ? Or any good method suggested?

(If you think it may be another question, tell me and I will raise the points since I don't
want to open another question. Thanks. :> )
0
 
LVL 22

Expert Comment

by:nietod
ID: 1419237
You can end a thread/process with ExitThread()/ExitProcess(), but you don't have to.  If you return from the main thread's/procedure's entry point procedure the thread/process will also end.  (Actually you end up returning to a small procedure witten by the OS that will end up calling the exit procedure for you.  This is the most common--and safest--way to end a thread or proccess.

>> Moreover, if the Thread is deadlock or whatever reason, it
?> takes a long time to finish,  I need to terminate it. If in this
>> case, using TerminateThread the memory may not be released.
>> Can I use ExitThread outside the function creating the Thread(i.e
>> AsynFileCopy from the above example) ? Or any good method
>> suggested?
No, you can't call ExitThread().  That ends the thread calling ExitThread(), not another thread.  Thus a working thread can't use ExitThread() to end a locked up thread, it ends itself instead of the other thread.  You can use TerminateThread for that--but should avoid it if possible, and it almost always is possible.  Why is the thread locked up?  Can it detect it and exit itself?  Is there a problem elsewhere that is causing the thread to be locked?  Can it be fixed?

0
 
LVL 2

Author Comment

by:Torus
ID: 1419238
What I mean is for example

Function AsyncFileCopy() as long
   FileCopy source, destination
end function

Command1_click()
   ExitThread
end sub

If the AsyncFileCopy thread is running, can I press command1 button to exit the thread?


>>.  Why is the thread locked up?  Can it detect
>>     it and exit itself?  Is there a problem elsewhere that is causing the thread to be
>>     locked?  Can it be fixed?

I find that there is a Ras API to kick off the DUN in NT(RasDlgDial something like that). The function only returns the result provided that error, user presses the cancel function or connection success. However, if the number of redials are finished, a Msgbox will appear
to ask to redial or not. In this case, it should have human intervention before the function exits. So if the API is in the thread, it will be held if no one press the button.

Thanks
0
 
LVL 22

Expert Comment

by:nietod
ID: 1419239
>> If the AsyncFileCopy thread is running, can I press command1 button to exit the thread?
Probably not.  If the file copying thread created the command 1 button, and has a message loop so that the command1_click is executed in the context of the thread, yes then it will work.  However, if the procedure is called in the context of a different thread, then that thread will be terminated, not the one that is copying.    Note also that terminating a thread like that is still not necessarily safe.  (its okay if you are careful, but may cause problems if you are not.)  

>> So if the API is in the thread, it will be held if no one press the button.
For this, you could start up a 2nd thread whose only function is to call that function and wait for it to return.  The main thread could continue to function (since it is not waiting for the function to return), so it could put up a dialog box with a cancel button.  I the user cancels the wait  (or you could be using a timer to cancel the wait after a certain time.)  Then you could use TerminateThread() to kill the other thread.  This is one of the times when it makes sense to kill a thread.  Note the design I suggested.  The thread that gets killed has no user interface features.  It does not create windows.  It does not do anything complex.  It simply calls another function and reports a return value to the main thread.  Keep that thread simple so that it will be safe to kill it.  If that thread created the dialog box with the cancel button, then it would be much more dangerious to kill it.
0
 
LVL 2

Author Comment

by:Torus
ID: 1419240
But if a API called in the thread should put up a dialog box(assume no one will touch the screen) and I need to terminate the thread after certain of time, TerminateThread should be used? Any code should be added so that the thread should be completely clear.
Very complex?
0
 
LVL 22

Expert Comment

by:nietod
ID: 1419241
I would try to avoid using TerminateThread() on a thread that does input (has windows), or on that creates "Windows objects", i.e that opens/creates handles provided by the Windows OS.  You may not be able to, but I would try.  Some people try to use TerminateThread/Process as part of the "normal" program  flow of their application, which is inappropriate.  Ussually you can duplicate the effect with a good program design,  but these programs use these procedures instead.  Your case with the locked up call to an API is not like that.
0
 
LVL 2

Author Comment

by:Torus
ID: 1419242
Anyway, thanks for you answer
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how to programmatically preset the "Pages per Sheet" option that's available with most printer drivers.   This setting lets you do "n-Up" printing, where two, four, or more pages are printed on each sheet of paper. If your …
This article describes a technique for converting RTF (Rich Text Format) data to HTML and provides C++ source that does it all in just a few lines of code. Although RTF is coming to be considered a "legacy" format, it is still in common use... po…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question