简体   繁体   中英

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?

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.

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.

最简洁的方法是向您的线程发送一条消息(或通过事件以其他方式指示),该提示应该终止,并允许其释放资源并退出其入口点功能。

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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM