【问题标题】:Is it possible to deallocate C __thread thread-local memory once the thread exited?线程退出后是否可以释放 C __thread 线程本地内存?
【发布时间】:2020-04-12 06:49:00
【问题描述】:

我有一个线程安全的函数,我想分配一个动态的线程本地内存缓冲区来独立使用它,并且一旦线程退出就能够释放它。这是演示:

void func_needs_storage(void) {
    static __thread void* tlb = NULL;

    if (!tlb)
        tlb = malloc(sizeof(int));

    printf("Thread id: %08lx, local tlb address is: %08lx\n",
            (uintptr_t)pthread_self(), (uintptr_t)tlb);
}

void* thread_func(void *) {
    for (int i = 0; i < 3; ++i)
        func_needs_storage();

    return NULL;
}

int main() {
    pthread_t threads[3];
    for (int i = 0; i < sizeof(threads) / sizeof(*threads); ++i)
        if (pthread_create(&threads[i], NULL, thread_func, NULL))
            return 1;

    for (int i = 0; i < sizeof(threads) / sizeof(*threads); ++i)
        if (pthread_join(threads[i], NULL))
            return 2;

    return 0;
}

请注意,我不能thread_func 中分配/释放内存 输出是:

Thread id: 7efda7cdd700, local tlb address is: 7efda0000b20 <-- 1st thread
Thread id: 7efda7cdd700, local tlb address is: 7efda0000b20
Thread id: 7efda84de700, local tlb address is: 7efda0000f50 <-- 2nd thread
Thread id: 7efda84de700, local tlb address is: 7efda0000f50
Thread id: 7efda8cdf700, local tlb address is: 7efda0000f70 <-- 3rd thread
Thread id: 7efda8cdf700, local tlb address is: 7efda0000f70

这是一种魅力,但不幸的是,这段代码造成了不可避免的内存泄漏:(

这里func_needs_storage()是一个需要临时缓冲区来处理一些数据的函数,它可能会被多次调用。它使用的内存应该是动态的,并且可能非常大(高达兆字节)并且几乎不能放在堆栈上。我不想在每次调用函数时都分配缓冲区,所以我将指向它的指针存储在线程局部静态变量中,每个线程都是唯一的。

问题是:当线程退出并且**保证**不再使用此内存时,是否可以在 C 中解除分配此线程本地内存缓冲区?也许我应该使用一些pthread API 或者以某种方式声明我的变量而不是__thread?编译器是最新的gcc/clang,操作系统是archlinux/freebsd。

作为 C++ 中的参考示例,我可以将缓冲区包装在 ThreadLocalStorage 类中,并创建析构函数来释放其内部内存。然后,如果一个声明一个static thread_local ThreadLocalStorage,一旦这个线程退出,它的析构函数就会被调用。

【问题讨论】:

  • 是否可以更改func_needs_storage 的签名(添加参数)?
  • @1201ProgramAlarm 可能,取决于您的具体建议
  • 您不能解除分配线程本地存储,但由于每个线程只需要 4 或 8 个字节,您不必担心这一点。线程需要调用 free() 以避免泄漏。
  • 它使用的内存应该是动态的,并且可能非常大(高达兆字节)并且几乎不能放在堆栈上。为什么不能 内存放在堆栈上?你有complete control over the size of the stack used for a POSIX thread
  • @AndrewHenle 说得好,安德鲁,我明天去看看

标签: c multithreading thread-local thread-local-storage


【解决方案1】:

我回来了。我已经使用了pthread_key_create()pthread_setspecific()pthread_getspecific() 函数来解决我的任务,我想与您分享我的解决方案,希望它对某人有所帮助。

static pthread_key_t key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;

void key_destructor(void* tlb) {
    printf("Thread id: %08lx, deallocate local tlb address: %08lx\n",
        (uintptr_t)pthread_self(), (uintptr_t)tlb);

    free(tlb);
}

void make_key_once(void) {
    pthread_key_create(&key, key_destructor /* or just "free" */);
}

void func_needs_storage(void) {
    pthread_once(&key_once, make_key_once);

    void* tlb = NULL;
    if ((tlb = pthread_getspecific(key)) == NULL) 
    {
        tlb = malloc(sizeof(int));
        pthread_setspecific(key, tlb);
    }

    printf("Thread id: %08lx, local tlb address is: %08lx\n",
        (uintptr_t)pthread_self(), (uintptr_t)tlb);
}

void* thread_func(void *) {
    for (int i = 0; i < 3; ++i)
        func_needs_storage();

    return NULL;
}

int main() {
    pthread_t threads[3];
    for (int i = 0; i < sizeof(threads) / sizeof(*threads); ++i)
        if (pthread_create(&threads[i], NULL, thread_func, NULL))
            return 1;

    for (int i = 0; i < sizeof(threads) / sizeof(*threads); ++i)
        if (pthread_join(threads[i], NULL))
            return 2;

    return 0;
}

输出是:

Thread id: 881b309c0, local tlb address is: 200bb81e0
Thread id: 881b309c0, local tlb address is: 200bb81e0
Thread id: 881b309c0, local tlb address is: 200bb81e0
Thread id: 881b309c0, deallocate local tlb address: 200bb81e0
Thread id: 881b30e40, local tlb address is: 200bb81e0
Thread id: 881b30e40, local tlb address is: 200bb81e0
Thread id: 881b30e40, local tlb address is: 200bb81e0
Thread id: 881b30e40, deallocate local tlb address: 200bb81e0
Thread id: 881b312c0, local tlb address is: 200bb81e0
Thread id: 881b312c0, local tlb address is: 200bb81e0
Thread id: 881b312c0, local tlb address is: 200bb81e0
Thread id: 881b312c0, deallocate local tlb address: 200bb81e0

内存被重用。让我们在 func_needs_storage() 中添加一些延迟来证明它有效:

Thread id: 8815e49c0[0], local tlb address is: 20062c1e0{0}
Thread id: 8815e52c0[1], local tlb address is: 20062c300{1}
Thread id: 8815e4e40[2], local tlb address is: 20062c2e0{2}
Thread id: 8815e4e40[2], local tlb address is: 20062c2e0{2}
Thread id: 8815e49c0[0], local tlb address is: 20062c1e0{0}
Thread id: 8815e52c0[1], local tlb address is: 20062c300{1}
Thread id: 8815e49c0[0], local tlb address is: 20062c1e0{0}
Thread id: 8815e49c0[0], deallocate local tlb address: 20062c1e0{0}
Thread id: 8815e4e40[2], local tlb address is: 20062c2e0{2}
Thread id: 8815e4e40[2], deallocate local tlb address: 20062c2e0{2}
Thread id: 8815e52c0[1], local tlb address is: 20062c300{1}
Thread id: 8815e52c0[1], deallocate local tlb address: 20062c300{1}

如果你没有像我一样被限制在 C 语言中并且允许在你的代码中使用 C++,请使用 thread_local storage class specifier 对象的析构函数将在线程上为每个 thread_local 对象调用终止使释放FD的内存成为可能。

专业提示:仔细查看操作系统的线程管理系统(它如何存储 TLS 区域并处理线程终止)。我们使用带有非常特殊的线程管理系统的 FreeBSD 9 fork。

祝你好运!

【讨论】:

    【解决方案2】:

    假设您不使用 pthread_cancel() 或以其他方式终止正在运行的线程,请将 tlb 声明移动到文件范围并在 thread_func() 返回之前将 free() 它:

    static __thread void* tlb = NULL;
    
    void* thread_func(void *) {
        for (int i = 0; i < 3; ++i)
            func_needs_storage();
    
        free( tlb );
        return NULL;
    }
    

    【讨论】:

    • 我在thread_func中既不能分配也不能释放内存,请注意我的评论。该演示是最先进技术的简化版本。
    • @Netherwire 为什么不呢?
    • @Netherwire 那么你有一个设计问题,而不是代码问题。
    • @dbush 因为 thread_func 不是我的代码。分配内存的函数是我的桥库的一部分。 thread_func 只是表示一个入口点。
    【解决方案3】:

    与其在func_needs_storage 中使用线程局部变量,不如在thread_func 中分配内存,将其传递给func_needs_storage,然后在thread_func 完成时释放它。

    void func_needs_storage(void *tlb) {
    
        printf("Thread id: %08lx, local tlb address is: %08lx\n",
                (uintptr_t)pthread_self(), (uintptr_t)tlb);
    }
    
    void* thread_func(void *) {
        void *tlb = malloc(sizeof(int));
        for (int i = 0; i < 3; ++i)
            func_needs_storage(tlb);
    
        free(tlb);
        return NULL;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 2023-04-10
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多