0
我的代碼:爲什麼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倍的析構函數,爲什麼呢?
'pthread_key_t'沒有析構函數。這很簡單c。 – user0042
我回滾到C++標記,因爲代碼顯然是C++。這種語言的東西應該先清除。如果這是爲了解決C問題,請提供C代碼。但看着它,我會認爲這不是一個語言問題,而是一個關於'pthread_key_t'如何工作的問題。 –
爲什麼不使用std :: threads? – 2017-09-15 09:09:18