简体   繁体   中英

Can I close/terminate an running thread from its thread function?

I have created a thread, with a custom thread function. I have a condition in the thread function that if it becomes true, I want to close the thread from inside the thread function.

Is it possible?

您可以从线程返回,如果要返回某个值,则可以在该线程上使用pthread_join

I assume you are using pthread for the thread functionlaity. You can call the pthread_detach () function in your custom thread function after creating the thread. In the created thread just returning from the thread function will be sufficient to close the thread and release all the resources associated with the thread.

For PThreads there are two ways to end a thread cleanly .

  • Detached the thread using pthread_detach() . To end it then call pthread_exit() . To find a thread's phtread-id from inside the thread itself use phtread_self() .
  • Call pthread_exit() and have another thread call pthread_join() on the pthread-id received when creating the thread that ended.

If you miss to call pthread_join() on a thread not having been detached by calling pthread_detach() , the resources in use by the thread will not be released, even after the thread ended.

This could lead to a shortage on memory and/or other system resources. Take care this does not happen.


A third was to end a thread is to just cancel it using pthread_cancel() , which typically isn't initated by the thread itself (as I could just use one of the two ways described above to end itself), but from another thread in the situation where the thread to end is not aware of this and could not be notified to do so.

The need to cancel a thread should rarely arise, and if it does one might start to overthink the program's design.

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