pthread_cleanup

執行緒可以安排它退出時需要調用的函式,這樣的函式稱為執行緒清理處理程式,執行緒可以建立多個清理處理程式。處理程式記錄在棧中,也就是說它們的執行順序與它們註冊時的順序相反。

基本介紹

  • 外文名:pthread_cleanup
  • 相關:來註冊清理函式rtn
  • 執行條件:調用pthread_exit
  • 執行條件:作為對取消執行緒請求
函式簡介,頭檔案,函式聲明,參數,編譯連結參數,注意事項,示例,

函式簡介

執行緒清理處理程式
pthread_cleanup_push來註冊清理函式rtn,這個函式有一個參數arg。在以下三種情形之一發生時,註冊的清理函式被執行:
1)調用pthread_exit。
2)作為對取消執行緒請求(pthread_cancel)的回響。
3)以非0參數調用pthread_cleanup_pop。

頭檔案

#include <pthread.h>

函式聲明

void pthread_cleanup_push(void (*rtn)(void *),void *arg);
void pthread_cleanup_pop(int execute);

參數

rtn 處理程式入口地址
arg 傳遞給處理函式的參數

編譯連結參數

-pthread

注意事項

1)如果執行緒只是由於簡單的返回而終止的,則清除函式不會被調用。
2)如果pthread_cleanup_pop被傳遞0參數,則清除函式不會被調用,但是會清除處於棧頂的清理函式。

示例

#include<stdlib.h>#include<stdio.h>#include<unistd.h>#include<pthread.h>voidclean_fun1(void*arg){printf("thisiscleanfun1\n");}voidclean_fun2(void*arg){printf("thisiscleanfun2\n");}void*thread_fun(void*arg){pthread_cleanup_push(clean_fun1,NULL);pthread_cleanup_push(clean_fun2,NULL);sleep(100);//這裡要注意,如果將sleep(100);換成while(1);的話,程式會一直暫停.push和pop要成對出現.//因為while(1);運行的太快,執行緒不接受cancel信號//while(1);pthread_cleanup_pop(0);pthread_cleanup_pop(0);returnNULL;}intmain(){pthread_ttid1;interr;err=pthread_create(&tid1,NULL,thread_fun,NULL);if(err!=0){perror("pthread_create");exit(0);}sleep(3);//printf("test\n");err=pthread_cancel(tid1);if(err!=0){perror("cancelerror:");exit(0);}err=pthread_join(tid1,NULL);if(err!=0){perror("pthread_joinerror:");exit(0);}return0;}

相關詞條

熱門詞條

聯絡我們