linux线程系列(5)线程清理和控制函数

来源:互联网 发布:手机淘宝点购买没反应 编辑:程序博客网 时间:2024/06/05 10:03

    线程清理函数有两个push和pop函数:

#include <pthread.h>void pthread_cleanup_push(void (*rtn)(void *), void* arg);void pthread_cleanup_pop(int execute);返回: 成功返回0,否则返回错误编号参数rtn:清理函数指针arg:调用清理函数传递的参数execute:值1时执行线程清理函数, 值0时不执行线程清理函数。

    这两个函数在子线程中被调用,必须成对出现(有push,必须有pop),当子线程结束的时候,如果execute的值为非零,push函数中的清理函数就会被执行。
子线程结束包括子线程调用return、调用pthread_exit、响应取消请求(其它线程调用pthread_canel函数,取消该线程)等。
由于采用了栈的机制,先push的清理函数后执行,如下面代码,首先打印second clean func,再打印first clean func:
#include <pthread.h>#include <stdlib.h>#include <stdio.h>//定义线程清理函数void clean_fun(void &arg){    char *s = (char*)arg;    printf("clean_fun: %s\n", s);}void* th_fun(void *arg){    int execute = (int)arg;    pthread_cleanup_push(clean_fun, "first clean func");         pthread_cleanup_push(clean_fun, "second clean func");        printf("thread running %lx\n", pthread_self());    pthread_clean_pop(execute);    pthread_clean_pop(execute);        return (void*)0;}int main(){    int err;    pthread_t th1, th2;        if((err = pthread_create(&th2, NULL, th_fun, (void*)1)) != 0)    {        perror("pthread create error");        return -1;    }        pthread_join(th1, NULL);    printf("th1(%lx) finished\n", th1);        if((err = pthread_create(&th2, NULL, th_fun, (void*)1)) != 0)    {        perror("pthread create error");        return -1;    }        pthread_join(th2, NULL);    printf("th2(%lx) finished\n", th2);    return 0;}


原创粉丝点击