MichaelXanadu
MichaelXanadu

Reputation: 505

How to end _beginthreadex()?

Inside my desktop application I have created a simple thread by using _beginthreadex(...). I wonder what happens if my application will be closed (without explicitly closing the thread)? Will all resources inside the thread be cleared automatically? I have doubts. So I like to end the thread when my application will be closed. I wonder what would be the best practise? Using _endthreadex is only possible inside(!) the thread and something like TerminateThread(...) does not seems to work (infinite loop). Do you have some advices?

Upvotes: 0

Views: 5336

Answers (4)

kfsone
kfsone

Reputation: 24249

To close the thread, you need to call CloseHandle() with the handle returned by _beginthreadex.

The thread is part of the process, so when the process terminates it will take the thread with it and the operating system will resume ownership of everything the two own, so all the resources will be released.

Bear in mind that if you have not forewarned the thread that the-end-is-nigh, it may be in the middle of some work when it ends. If it is in the middle of using any system or external resources, they will be released but may be in a funky state (e.g. a file may be partially written, etc).

See also http://www.bogotobogo.com/cplusplus/multithreading_win32A.php

Note: Using CloseHandle() is only for _beginthreadex and not if you are using _beginthread. See http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.90).aspx

Upvotes: 0

Len Holgate
Len Holgate

Reputation: 21616

When main exits your other threads will be destroyed.

It's best to have main wait on your other threads, using their handles, and send them a message (using an event, perhaps) to signal them to exit. Main can then signal the event and wait for the other threads to complete what they were doing and exit cleanly. Of course this requires that the threads check the event periodically to see if they need to exit.

Upvotes: 1

Duncan Smith
Duncan Smith

Reputation: 538

The tidiest way is to send your thread(s) a message (or otherwise indicate via an event) that the tread should terminate and allow it to free its resources and exit its entry point function.

Upvotes: 0

moswald
moswald

Reputation: 11677

When the main thread exits, the app and all of its resources are cleaned up. This will include other threads and their resources.

Also, post the code you have for TerminateThread, because it works.

Upvotes: 0

Related Questions