zoukankan      html  css  js  c++  java
  • 线程4——清理

    void pthread_cleanup_push(void (*routine)(void *),void *arg);

      第一个参数:指向需要执行的函数   arg为该函数的参数

    void pthread_cleanup_pop(int execute);

      int整形数字,非零为执行清理函数

    两个函数成对使用

    先把函数写进routine里,调用push函数去装routine,然后在用pop让push发挥作用

    什么时候会触发push函数?

    1、线程结束时,调用pthread_exit()

    2、取消线程相应pthread_cancel

    3、非零参数调用pthread_cleanup_pop()

    1     pthread_cleanup_push(cleanup_handler1,(void*)1);
    2     pthread_cleanup_push(cleanup_handler2,(void*)2);
    3     pthread_cleanup_push(cleanup_handler3,(void*)3);
    4     //按照1、2、3函数顺序进行压栈
    5 
    6     pthread_cleanup_pop(1);
    7     pthread_cleanup_pop(1);
    8     pthread_cleanup_pop(1);
    9     pthread_exit(0);

    最先被执行的时handler3,然后handler2 1

    线程清理示例:

     1 void* thread1(void *arg)
     2 {
     3     int *p;
     4     p = (int *)malloc(sizeof(int));
     5         pthread_cleanup_push(cleanup_handler,(void*)3);
     6         pthread_mutex_lock(&lock);
     7         //此线程主要功能代码
     8         //…….
     9         pthread_cleanup_pop(1);
    10 
    11 }
    12 void cleanup_handler (void *arg)
    13 {
    14     free(arg);
    15         pthread_mutex_unlock(&lock);
    16 }
  • 相关阅读:
    13点睛Spring4.1-Spring EL
    12点睛Spring4.1-Spring Aware
    11点睛Spring4.1-Property Editor
    10点睛Spring4.1-Application Event
    09点睛Spring4.1-AOP
    08点睛Spring4.1-Profile
    07点睛Spring4.1-BeanPostProcessor
    06点睛Spring4.1-Bean的初始化和销毁
    05点睛Spring4.1-国际化
    Solaris 11 配置IP地址
  • 原文地址:https://www.cnblogs.com/qifeng1024/p/11674256.html
Copyright © 2011-2022 走看看