Cancellation Point

What is Cancellation Point?

cancelability type 設為 PTHREAD_CANCEL_DEFERRED 時,thread 收到 cancellation request 時並不會直接結束,而是會繼續執行直到遇到一個 cancellation point 才會結束

Why we need Cancellation Point?

想像下列情況:

  1. thread 用 malloc() 取得了一塊記憶體,結果在還沒 free() 之前就被 cancel 了
  2. thread 求取了 mutex lock,結果還沒放掉鎖就被 cancel 了

What makes a good Cancellation Point?

Block System Call

相比於一般的指令(如 i++ 可能由多個 CPU instruction 組成,中途中斷會有問題),blocking system call 是理想的 cancellation point,原因是:

明確的執行邊界

  • Thread 調用 blocking system call 時會進入 kernel space
  • 這是一個清晰的狀態轉換點,適合檢查 cancellation request

等待期間的安全性

  • Blocking system call 會讓 thread 進入等待狀態(等待 I/O、鎖、或時間)
  • 在等待期間,thread 沒有持有關鍵的中間狀態
  • 此時接受 cancellation 不會破壞資料一致性

系統層級的保證

  • 如果在 blocking system call 中被 cancel,系統保證:
    • 返回到一致的狀態(沒有半完成的操作)
    • 資源(如 file descriptor)仍然有效
    • 可以安全地返回錯誤碼

Resource Management

Block system call 保證 instruction 執行層面的安全,但是 resource management 是程式設計者必須自行保證其安全性的(e.g. mutex lock, share resource, file management)


pthread_testcancel

Function Prototype

void pthread_testcancel(void);

Function

人工設定一個 cancellation point