Thread Cleanup Handler

Concept

exit handler 有些類似,但他只會在以下三種情況被下執行

  1. 當 thread 主動呼叫 pthread_exit
  2. thread 接受 cancellation request 後
  3. 呼叫 pthread_cleanup_pop(1)

在這三種情況,cleanup handler 會以 FILO 的方式被執行(類 stack)

pthread_cleanup_push

Function Prototype

void pthread_cleanup_push(void (*rtn)(void *), void *arg);
  • rtn 指向我們要作為 cleanup handler 的函數
  • arg 則是我們要傳的參數

Function

rtn 註冊到 cleanup handler 的 stack

pthread_cleanup_pop

Function Prototype

void pthread_cleanup_pop(int execute);

Function

將 cleanup handler stack 最上方的東東拿掉

  • execute=1:會先執行該 error handler 才刪掉
  • execute=0:直接拿掉不執行

Remark

push 和 pop 兩個函數一定要成對使用,如果 thread 的 start function 正常返回,並不會像 error handler 一樣自動執行 thread cleanup handler

因此如有使用 push 則我們必須在 start function 結束前將其 pop 掉

void cleanup_mutex(void *arg) {
    pthread_mutex_t *mutex = (pthread_mutex_t *)arg;
    pthread_mutex_unlock(mutex);
    printf("Mutex已被清理函數解鎖\n");
}
 
void *thread_function(void *arg) {
    pthread_mutex_t *mutex = (pthread_mutex_t *)arg;
    
    pthread_mutex_lock(mutex);
    pthread_cleanup_push(cleanup_mutex, mutex);
    
    // 執行一些可能被取消或拋出錯誤的操作
    // ...
    
    pthread_cleanup_pop(1);  // 正常結束時也執行清理
    return NULL;
}