一旦线程退出,是否可以释放 C __thread 线程本地内存?

Is it possible to deallocate C __thread thread-local memory once the thread exited?

我有一个线程安全函数,我想分配一个动态线程局部内存缓冲区以独立使用它,并能够在线程退出后释放它。这是演示:

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;
}

Note that I can't allocate/free memory in the thread_func The output is:

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 OS 是 archlinux/freebsd.

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

假设您不使用 pthread_cancel() 或以其他方式终止 运行 线程,将 tlb 声明移动到文件范围并 free() 它就在 [=14] 之前=] returns:

static __thread void* tlb = NULL;

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

    free( tlb );
    return NULL;
}

与其在 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;
}

我回来了。我已经使用 pthread_key_create(), pthread_setspecific() and 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 的内存。

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

祝你好运!