Linux--多线程之线程资源回收pthread

    xiaoxiao2021-12-14  21

    #include "apue.h" /** 作用:线程结束后的资源回收 1.pthread_cleanup_push与pthread_cleanup_pop要成对使用 否则编译器会瞎报错误 pthread_cleanup_push的执行顺序和声明顺序相反 当相遇取消请求时 清理函数对也生效 */ void cleanup(void *ar){ printf(" %s \n",(char *)ar); } void *thread_fun(void *person1){ int i = 0; pthread_cleanup_push(cleanup,"pthread_cleanup_push 1");//后执行 pthread_cleanup_push(cleanup,"pthread_cleanup_push 2");//先执行 while(1) { printf("hahahah %d \n",i++); sleep(1); if(i==3) break; } pthread_cleanup_pop(1);// 如果参数为0 必须位于pthread_exit后面 才能生效 pthread_cleanup_pop(1); pthread_exit((void *)2); //return NULL; printf("behind of pthread_exit \n");//不执行 } int main(){ pthread_t tid; int err; //创建线程 err = pthread_create(&tid,NULL,thread_fun,NULL); if(err!=0){ perror(" fail to create thread "); return -1; } printf("succeed to create thread tid = %lu \n ",tid); //主线程退出 pthread_exit(NULL);//always succeeds }
    转载请注明原文地址: https://ju.6miu.com/read-970959.html

    最新回复(0)