使用 pthread tls destructor 时遇到的问题

使用 pthread 线程时,可以通过 pthread_key_create() 这个 API,给新创建的线程添加一个回调函数,在线程退出时会被系统调用到,通常用于线程相关资源的清理,等等。

int pthread_key_create(
    pthread_key_t *key, void (*destructor)(void*));

特别要注意的是,在 destructor 被回调时,其参数肯定不为空,但此时 对应的 tls 已经被清空! 所以,如果 destructor 里有依赖 tls 的,其运行结果肯定跟预期的不一样。

写代码的时候没注意,出了问题也没有头绪,仔细看了 pthread_key_create 的文档 才清楚:

An optional destructor function may be associated with each key value. At thread exit, if a key value has a non-NULL destructor pointer, and the thread has a non-NULL value associated with that key, the value of the key is set to NULL, and then the function pointed to is called with the previously associated value as its sole argument. The order of destructor calls is unspecified if more than one destructor exists for a thread when it exits.

Read More: