pthread_self()返回的线程ID与gettid(2)调用返回的内核线程ID不同 [英] The thread ID returned by pthread_self() is not the same thing as the kernel thread ID returned by a call to gettid(2)

查看:152
本文介绍了pthread_self()返回的线程ID与gettid(2)调用返回的内核线程ID不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该引用来自pthread_self()的手册页.

That quote is from the man page of pthread_self().

那么,我应该在什么基础上决定应该使用pthread_self还是gettid来确定哪个线程正在运行该函数?

So, on what basis should I decide whether I should use pthread_self or gettid to determine which thread is running the function?

两者都是不可携带的.
为什么有两个不同的函数来获取线程ID?

Both are non portable.
Why are there two different functions to get the thread ID?

推荐答案

因此,我应该在什么基础上决定应该使用pthread_self还是使用pthread_self? 要确定哪个线程正在运行该函数?

So, on what basis should I decide whether I should use pthread_self or gettid to determine which thread is running the function?

无论何时要在应用程序中标识线程,都应始终使用pthread_self(). gettid() 可以用于某些目的(如果您知道它是Linux).例如,gettid()可用于获取线程特定种子的种子(用于srand()).

You should always use pthread_self() whenever you want to identify a thread within your application. gettid() can be used for certain purposes and if you know it's Linux. For example, gettid() can be used to get seed for a thread specific seed (used in srand()).

两者都是不可携带的.

Both are non portable.

这并非完全正确. gettid()不可移植,因为它具有Linux特定功能.但是pthread_self()是可移植的,只要您不对其表示形式做任何假设即可.

This is not entirely true. gettid() is not portable as its a Linux specific function. But pthread_self() is portable as long as you don't make any assumptions about its representation.

例如,以下是可移植的.

For example, the following is not portable.

printf("Thread ID is: %ld", (long) pthread_self());

,因为不能保证pthread_self()都是某种整数.但是

as there's no guarantee that whatever pthread_self() is going to be an integer of some sort. But

pthread_t my_tid; //filled elsewhere

pthread_t tid = pthread_self();

if( pthread_equal(my_tid, tid) ) {
   /* do stuff */
}

是完全可移植的.

前者是不可移植的,因为它假定线程ID是整数,而后者不是.

The former is not portable because it assumes that thread id is an integer whereas the latter is not.

为什么有两个不同的函数来获取线程ID?

Why are there two different functions to get the thread ID?

它们不是获得相同值的两种不同方法.一个(pthread_self()由线程库(pthreads)提供,而另一个(gettid()是特定于操作系统的功能.不同的OS可能会提供不同的接口/syscall以获取类似于gettid()的线程ID.因此,不能依赖可移植应用程序中的gettid().

They are not two different ways to get the same value. One (pthread_self() is provided by the thread library (pthreads) while the other (gettid()is an OS-specific function. A different OS may provide a different interface/syscall to get thread ID similar to gettid(). So you can't rely on gettid() in a portable application.

这篇关于pthread_self()返回的线程ID与gettid(2)调用返回的内核线程ID不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆