thread 的取消狀態有啟用 (預設) 和停用,可由 pthread_setcancelstate() 設定。停用時收到取消請求暫不處理 (queued),直到啟用。收到取消請求且啟用時,type 決定取消何時進行。
thread 的取消 type 有 deferred (預設) 及 asynchronous,可由 pthread_setcanceltype() 設定。Asynchronous 表示可在任何時間點取消,但系統不保證立即進行。Deferred 表示直到 thread 呼叫到含有取消點 (cancellation point) 的函數才進行取消動作。
取消動作依序包括:
- pop 每個 Cancellation clean-up handlers 並執行。(見 pthread_cleanup_push())
- 呼叫 thread-specific data destructors (見 pthread_key_create())
- thread 結束 (見 pthread_exit())
Linux 用 signal 實作 thread 取消,在 NPTL 是第一個 real-time signal (也就是 signal 32)。
pthread_cancel() MT-safe
async-cancel-safe 函數:能夠在啟用 asynchronous 取消的應用安全使用的函數,包括 pthread_cancel()、pthread_setcancelstate()、pthread_setcanceltype()。
必須含有取消點的函數:包括 sleeps() 等,列表見 man pthreads
- pthread_testcanel():測試是否取消
應用:有些 thread 設計是無窮的迴圈,其它 thread 呼叫 pthread_cancel() 作為結束。
參考來源
- man pthread_canel
- man pthreads
沒有留言:
張貼留言