日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

线程清理函数

發布時間:2023/11/30 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程清理函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

一、線程清理函數

#include <pthread.h> void ptread_clean_push(void (*rtn) (void *), void *arg); 注冊清理函數,押棧 void ptread_clean_pop(int excute); 清理函數,出棧

分析:這兩個函數是成對出現的,少一個會導致編譯不通過

參數詳解:

  • pthread_cleanup_push:該函數的第一個參數是清理函數,參數是void*,返回值是void類型的,第二個函數是押棧需要傳的參數。
  • pthread_cleanup_pop:出棧,調用清理函數,其中只有一個參數,該參數是非零會響應清理函數,是0的話,不做處理

注意該處理函數是被放在棧區,所以先進棧的后出棧,也就是說先進棧的函數,最后被調用。

當有以下三種操作的時候會調用清理函數:

  • 調用pthread_exit()函數,會響應清理處理函數。
  • 用非零的函數調用pthread_cleanup_pop()函數。
  • 響應取消請求。

?

二、程序清單

測試代碼:

#include <stdio.h> #include <unistd.h> #include <pthread.h>void *first_cleanup(void *arg) {printf("this is clenup function %s\n", arg); }void *second_cleanup(void *arg) {printf("this is clenup function %s\n", arg); }void *thread_fun1(void *arg) {sleep(1);printf("this is thread 1\n");pthread_cleanup_push(&first_cleanup, "thread 1");pthread_cleanup_push(&second_cleanup, "thread 1"); pthread_cleanup_pop(1);pthread_cleanup_pop(1); return (void*)0;} void *thread_fun2(void *arg) { sleep(2);printf("this is thread 2\n");pthread_cleanup_push(&first_cleanup, "thread 2");pthread_cleanup_push(&second_cleanup, "thread 2");pthread_exit((void*)0);pthread_cleanup_pop(0);pthread_cleanup_pop(0); } void *thread_fun3(void *arg) {sleep(3);printf("this is thread 3\n");pthread_cleanup_push(&first_cleanup, "thread 3");pthread_cleanup_push(&second_cleanup, "thread 3");pthread_cleanup_pop(0);pthread_cleanup_pop(0); pthread_exit((void*)0); } int main(){pthread_t tid1, tid2, tid3;pthread_create(&tid1, NULL, thread_fun1, NULL);pthread_create(&tid2, NULL, thread_fun2, NULL);pthread_create(&tid3, NULL, thread_fun3, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);pthread_join(tid3, NULL);return 0;}

輸出結果:?

?

分析pthread_cleanup_pop()中參數是非0時會調用清理處理函數,當參數是0的時候,pthread_cleanup_pop該函數的參數在pthread_exit()退出前調用無論是0還是非0,都會響應清理處理函數,但是pthread_exit()在pthread_cleanup_pop函數之后調用,pthread_cleanup_pop函數的參數是0的話,清理函數已經退出,所以就不會再調用到清理處理函數了。
?

三、參考資料

1.?線程的清理處理程序

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的线程清理函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。