2017-09-15 27 views
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回と呼ばれるデストラクタ、なぜ?

+0

'pthread_key_t'にはデストラクタがありません。それは普通です。 – user0042

+0

私はコードが明らかにC++であるため、C++タグにロールバックしました。この言語のものは最初にクリアする必要があります。これがCの質問であれば、Cコードを提示してください。しかし、それを見ると、言語的な問題ではなく、 'pthread_key_t'がどのように動作するのかという疑問があると思います。 –

+0

std :: threadsを使わないのはなぜですか? –

答えて

1
The documentation holds the answer

(破壊少なくともPTHREAD_DESTRUCTOR_ITERATIONS試みの後に)失われた記憶装置に、または無限ループのいずれかで生じ得るスレッド固有データデストラクタルーチンからpthread_setspecific()を呼び出します。

関連する問題