gpt4 book ai didi

c++ - 为什么 pthread_key_create 析构函数被调用了几次?

转载 作者:行者123 更新时间:2023-11-28 01:43:23 29 4
gpt4 key购买 nike

我的代码:

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次,为什么?

最佳答案

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.

关于c++ - 为什么 pthread_key_create 析构函数被调用了几次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46235369/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com