天天看点

Android native RIL 如何判断线程是否是主线程?

最近遇到一个问题,需要在Android RIL层判断当前是线程是否是主线程,如果是主线程需要执行一些逻辑,如果是非主线程,那就执行另外的逻辑。下面就是简单的sample了。

#include <unistd.h>
pid_t thread_id = gettid();
pid_t process_id = getpid();
if (thread_id == process_id) {
    do anything;
} else {
    do others;
}
           

另外也简单介绍一下pthread_self()这个就是线程的地址,和getpid()不是一个值。这个值是pthread_create()函数中的第一个参数。

#include <pthread.h>
pthread_t s_tid;
void init_thread(void) {
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    int result = pthread_create(&s_tid, &attr, loop, NULL);
    if (result != 0) {
        assert(0);
    }
}

void doLoop(void)  {
   if (!pthread_equal(pthread_self(), s_tid)) {
       // do anyting
    }
}
           

pthread_equal 返回值

如果 tid1 和 tid2 相等,pthread_equal() 将返回非零值,否则将返回零。如果 tid1 或 tid2 是无效的线程标识号,则结果无法预测。

线程相关的函数在不同的平台有不同的实现,使用的时候一定要注意平台的差异。