使用pthread_cleanup_push 遇到的问题

127 阅读1分钟

今天学习 Unix 编程中有关线程的部分的使用,写出了如下的测试程序

/*
    thread_2.c
        测试线程清理处理程序
    BeginnerC
*/
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
/*
    handle
        线程函数
    BeginnerC
*/
void* handle(void *argument)
{
    printf ("这是 %s 线程\n", __func__);
    pthread_exit((void*)0);
    return 0;
}
/*
    handle_2
        线程函数(二号)
    BeginnerC
*/
void* handle_2(void *argument)
{
    printf ("这是 %s 线程\n", __func__);
    pthread_exit((void*)0);
    return 0;
}
/*
    exit_handle
        线程清理退出函数(一号)
    BeginnerC
*/
void exit_handle(void *argument)
{
    printf("This is %s\n", __func__);
}
/*
    exit_handle_2
        线程清理退出函数(二号)
    BeginnerC
*/
void exit_handle_2(void *argument)
{
    printf("This is %s\n", __func__);
}
int main()
{
    pthread_t tid;
    pthread_cleanup_push(exit_handle, NULL);
    pthread_create(&tid, NULL, handle, NULL);
    pthread_create(&tid, NULL, handle_2, NULL);
    sleep(6);
    return 0;
}

而交付编译器编译的时候,也就出现了错误

输入图片说明

经过一番查询,我得知了错误的原因 blog.csdn.net/caianye/art…

输入图片说明

换而言之,pthread_cleanup_push 函数必须和 pthread_cleanup_pop 函数配合使用.

修订之后,程序给出了正确的结果

输入图片说明

/*
    thread_2.c
        测试线程清理处理程序
    BeginnerC
*/
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
/*
    handle
        线程函数
    BeginnerC
*/
void* handle(void *argument)
{
    printf ("这是 %s 线程\n", __func__);
    pthread_exit((void*)0);
    return 0;
}
/*
    handle_2
        线程函数(二号)
    BeginnerC
*/
void* handle_2(void *argument)
{
    printf ("这是 %s 线程\n", __func__);
    pthread_exit((void*)0);
    return 0;
}
/*
    exit_handle
        线程清理退出函数(一号)
    BeginnerC
*/
void exit_handle(void *argument)
{
    printf("This is %s\n", __func__);
}
/*
    exit_handle_2
        线程清理退出函数(二号)
    BeginnerC
*/
void exit_handle_2(void *argument)
{
    printf("This is %s\n", __func__);
}
int main()
{
    pthread_t tid;
    pthread_cleanup_push(exit_handle, NULL);
    pthread_create(&tid, NULL, handle, NULL);
    pthread_create(&tid, NULL, handle_2, NULL);
    pthread_cleanup_pop(0);
    sleep(6);
    return 0;
}

输入图片说明

我们也可使用非零参数调用 pthread_cleanup_pop 函数,这样就可以看到我们注册的清理处理程序了。

这也解答了我的疑惑:

第一,线程清理处理函数是针对全局的,它并不是针对特定线程的

第二,这样做的原因,是因为线程是资源共享的,而这组函数设计的目的,就在于释放资源,所以针对特定资源没有必要