Solved

ExitThread, ExitProcess and Closehandle

Posted on 1999-01-25
10
2,250 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
 
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article describes how to add a user-defined command button to the Windows 7 Explorer toolbar.  In the previous article (http://www.experts-exchange.com/A_2172.html), we saw how to put the Delete button back there where it belongs.  "Delete" is …
This article surveys and compares options for encoding and decoding base64 data.  It includes source code in C++ as well as examples of how to use standard Windows API functions for these tasks. We'll look at the algorithms — how encoding and decodi…
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…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

708 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now