pthread_create 在Android和Linux下返回的thread_id一个为正数一个为负数
Q
因需要移植linux下模块到android平台上去,由于判断了返回值和thread_id(是否大于0),导致模块线程无法正常启动(pthread_create返回成功)。
Android
通过分析Android源码(bionic),pthread_id是由指针强转为长整型数,如下:
// Publish the pthread_t and unlock the mutex to let the new thread start running.
*thread_out = __pthread_internal_add(thread);
pthread_t __pthread_internal_add(pthread_internal_t* thread)
{
ScopedWriteLock locker(&g_thread_list_lock);
// We insert at the head.
thread->next = g_thread_list;
thread->prev = nullptr;
if (thread->next != nullptr) {
thread->next->prev = thread;
}
g_thread_list = thread;
return reinterpret_cast<pthread_t>(thread); //指针强转, typedef long pthread_t;
}
Linux
分析Linux源码(glibc),pthread_id是强转为无符号长整型的数,如下:
/* Pass the descriptor to the caller. */
*newthread = (pthread_t) pd; // 指针强转,typedef unsigned long int pthread_t;
分析完源码发现果然问题都是自找的,官方手册也并没有说pthread_id返回一定是大于正整数,pthread_create返回0即成功:
so
判断返回值即可,无需判断thread_id!!!!!!