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

问题描述:

我的代码:为什么pthread_key_create析构函数被多次调用?

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

输出:

$ ./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 

有只有2个线程,而是叫5倍的析构函数,为什么呢?

+0

'pthread_key_t'没有析构函数。这很简单c。 – user0042

+0

我回滚到C++标记,因为代码显然是C++。这种语言的东西应该先清除。如果这是为了解决C问题,请提供C代码。但看着它,我会认为这不是一个语言问题,而是一个关于'pthread_key_t'如何工作的问题。 –

+0

为什么不使用std :: threads? – 2017-09-15 09:09:18

The documentation holds the answer

调用从一个特定的线程的数据析例程pthread_setspecific()可能会导致无论是在丢失的存储(在后破坏至少PTHREAD_DESTRUCTOR_ITERATIONS尝试)或无限循环。