pthread_cancel() function failed to terminate a thread

前端 未结 2 1279
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 03:48

I\'m using pthread_create() and pthread_cancel() functions to create a multithreaded program, but I noticed that pthread_cancel() did

相关标签:
2条回答
  • 2021-01-06 04:08

    The default cancel method of pthread_cancel() is delayed cancel.So when you invoke pthread_cancel(), it will not really cancel before the specified thread reach the cancel point.You shoud call pthread_setcanceltype to set another cancel method to your thread.

    0 讨论(0)
  • 2021-01-06 04:24

    By default your thread is created with the cancel type PTHREAD_CANCEL_DEFERRED, which means that you need to make sure that your thread has a so-called cancellation point. That is, a point where cancel requests are checked and reacted upon.

    This page contains a list of functions that are guaranteed to be cancellation points. Examples are some of the sleep() and pthread functions. You can also use pthread_testcancel() if you just need a function to purely test whether the thread has been canceled, and nothing else.

    Another option is to set your threads canceltype to be PTHREAD_CANCEL_ASYNCHRONOUS, by using pthread_setcanceltype(), which will make your thread cancelable even without cancellation points. However, the system is still free to choose when the thread should actually be canceled, and you'll need to take great care to make sure that the system isn't left in an inconsistent state when cancelled (typically means avoiding any system calls and similar - see the list of Async-cancel-safe functions - it's short!).

    In general, asynchronous cancellation should only be used for more or less "pure" processing threads, whereas threads performing system calls and similar are better implemented with deferred cancellation and careful placement of cancellation points.

    Also, as long as you are not detaching your thread (by either creating it detached through its attribute, or by calling pthread_detach() after it is created), you will need to call pthread_join() on the timer thread to make sure that all resources are cleaned up after canceling it. Otherwise you might end up in a state without any spare threading resources, where you cannot create any new threads.

    0 讨论(0)
提交回复
热议问题