diff --git a/src/bthread/key.cpp b/src/bthread/key.cpp index a4a08407db..ca5e079dfd 100644 --- a/src/bthread/key.cpp +++ b/src/bthread/key.cpp @@ -446,10 +446,14 @@ int bthread_setspecific(bthread_key_t key, void* data) { bthread::TaskGroup* const g = bthread::tls_task_group; if (g) { g->current_task()->local_storage.keytable = kt; - } - if (!bthread::tls_ever_created_keytable) { - bthread::tls_ever_created_keytable = true; - CHECK_EQ(0, butil::thread_atexit(bthread::cleanup_pthread, kt)); + } else { + // Only cleanup keytable created by pthread. + // keytable created by bthread will be deleted + // in `return_keytable' or `bthread_keytable_pool_destroy'. + if (!bthread::tls_ever_created_keytable) { + bthread::tls_ever_created_keytable = true; + CHECK_EQ(0, butil::thread_atexit(bthread::cleanup_pthread, kt)); + } } } return kt->set_data(key, data);