pthread 使用 pthread_cleanup_push 清理 int/array/struct 类型变量

问题描述 投票:0回答:1

这可能是一个转储问题,但我不熟悉多线程编程,并且用谷歌搜索了很多,但找不到有用的信息。假设我有一个线程的启动函数,它创建 int/array/struct 类型的局部变量,那么我需要从另一个线程

pthread_cancel
这个线程并像下面一样清理它(我知道它可能看起来有问题) ,如何清理那些存在内存泄漏的int/array/struct类型的变量?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

pthread_t handler;

static void cleanup_int(void* arg){ /* clean up int */ }
static void cleanup_array(void* arg){ /* clean up array */ }
static void cleanup_srtuct(void* arg){ /* clean up struct */ }

static void* thread_func(void* p) {
    handler = pthread_self();
    int num = 0;  // variable of int type
    unsigned char array[8] = {0};  // variable of array type
    struct struct_var;  // variable of user defined struct type

    pthread_cleanup_push(cleanup_int, &num);
    pthread_cleanup_push(cleanup_array, array);
    pthread_cleanup_push(cleanup_struct, &struct_var);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
    while (1) {
        printf("thread: %d\n", num);
        sleep(1);
    }
}
void main(void) {
    int count;
    pthread_t t;
   
    pthread_create(&t, NULL, thread_func, NULL);
    
    for(count = 0; count < 10; count++){
        printf("count = %d\n", count);
        if(count == 5){
            printf("terminate thread\n");
            pthread_cancel(handler);
        }
        sleep(1);
    }
}

我想知道如何清理那些没有明确清理例程的变量。感谢提前回答这个问题的人!

我用谷歌搜索了很多并尝试了一些简单的程序,但仍然不知道如何处理这些变量和/或其他用户定义的数据结构

c multithreading pthreads
1个回答
0
投票

如何清理那些存在内存泄漏的int/array/struct类型的变量?

如果您忽略我在评论中的建议以避免

pthread_cancel()
,这是一个非常好的经验法则:在程序中的任何给定点,您希望对线程取消带来的不良影响具有鲁棒性,需要执行的清理任务范围内清理回调提供的正是允许在同一点进行安全
pthread_exit()
调用所需的回调。

特别是,您不需要恢复存储或调整具有自动或线程存储持续时间的对象的值,例如普通局部变量,包括结构体、数组及其成员/元素。但是,如果您有这样的对象,其中包含指向动态分配对象的指针,那么您“可能”需要取消分配所指向的对象。根据您的程序的用途,您可能需要清理动态或静态分配的对象的值,特别是包括释放互斥体和以其他方式操作同步对象之类的内容。 另请注意:注册清理处理程序只是为了在之后立即弹出它是没有意义的。处理程序应该在创建需要它的语句之后立即推送(或者在之前,甚至,如果可以使其工作的话),并且只有在不再需要清理之后才应该弹出它。很多时候,应该使用非零参数来调用

pthread_cleanup_pop()

,这样通过运行它

就不需要清理了。

© www.soinside.com 2019 - 2024. All rights reserved.