为什么pthread_key_create析构函数被多次调用?

时间:2017-09-15 08:44:33

标签: c++ c++11 concurrency pthreads

我的代码:

Select COLUMN_NAME, DATA_TYPE From ALL_TAB_COLUMNS 
Where TABLE_NAME = UPPER('TAB NAME') and COLUMN_NAME = UPPER('COL NAME')

输出:

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

只有2个线程,但析构函数调用了5次,为什么?

1 个答案:

答案 0 :(得分:2)

The documentation holds the answer

  

从特定于线程的数据析构函数例程调用pthread_setspecific()可能导致存储丢失(至少PTHREAD_DESTRUCTOR_ITERATIONS次尝试销毁之后)或无限循环。