简体   繁体   中英

Why pthread_key_create destructor called several times?

My code:

const uptr kPthreadDestructorIterations = 2;

static pthread_key_t key;
static bool destructor_executed;

void destructor(void *arg) {
    uptr iter = reinterpret_cast<uptr>(arg);
    printf("before destructor, the pthread key is %ld\n", iter);
    if (iter > 1) {
        ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void *>(iter - 1)));
        return;
    }
    destructor_executed = true;
}

void *thread_func(void *arg) {
    uptr iter = reinterpret_cast<uptr>(arg);
    printf("thread_func, the pthread key is %ld\n", iter);
    return reinterpret_cast<void*>(pthread_setspecific(key, arg));
}

static void SpawnThread(uptr iteration) {
    destructor_executed = false;
    pthread_t tid;
    ASSERT_EQ(0, pthread_create(&tid, 0, &thread_func,
                reinterpret_cast<void *>(iteration)));
    void *retval;
    ASSERT_EQ(0, pthread_join(tid, &retval));
    ASSERT_EQ(0, retval);
}

int main(void) {
    ASSERT_EQ(0, pthread_key_create(&key, &destructor));
    SpawnThread(kPthreadDestructorIterations);
    //EXPECT_TRUE(destructor_executed);
    GOOGLE_CHECK(destructor_executed);
    SpawnThread(kPthreadDestructorIterations + 1);
    //EXPECT_FALSE(destructor_executed);
    GOOGLE_CHECK(destructor_executed);
    return 0;
}

the output:

$ ./pthread_key 2>&1
thread_func, the pthread key is 2
before destructor, the pthread key is 2
before destructor, the pthread key is 1
thread_func, the pthread key is 3
before destructor, the pthread key is 3
before destructor, the pthread key is 2
before destructor, the pthread key is 1

There only 2 threads, but the destructor called 5 times, why?

The documentation holds the answer :

Calling pthread_setspecific() from a thread-specific data destructor routine may result either in lost storage (after at least PTHREAD_DESTRUCTOR_ITERATIONS attempts at destruction) or in an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM