c - 线程退出后是否可以取消分配C __thread线程本地内存?

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

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

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,操作系统是archlinux/freebsd。

作为C++中的引用示例,我可以将缓冲区包装在ThreadLocalStorage类中,并使析构函数释放其内部内存。然后,如果声明static thread_local ThreadLocalStorage,则该线程退出后将调用其析构函数。

最佳答案

我回来了。我已经使用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与非常独特的线程管理系统结合使用。
祝你好运!

关于c - 线程退出后是否可以取消分配C __thread线程本地内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413673/

相关文章:

使用 pin、perf 和 valgrind 计算二进制文件执行的指令数

python - 如何将 Python bool 对象转换为 C int(或 C++ bool 值)(Python C API)

c# - 任务工厂和线程本地存储

c - 从 OS X 上 C 中的 dlopen()ed 动态库访问主程序全局结构/指针

c - GCC 添加了奇怪的时间变量

c# - 在 Dispatcher.Invoke 语句中抛出异常时,Dispatchers UnhandledException 处理程序未处理异常

java - ExecutorService 任务执行间歇性延迟

c - linux内核模块中的线程本地数据

c# - 在并行循环之间保留 ThreadLocal 是好还是坏?

java - 在以下情况下是否需要调用 ThreadLocal.remove