该引用来自 man page of pthread_self() .
那么,我应该根据什么来决定我应该使用 pthread_self
还是 gettid
来确定哪个线程正在运行该函数?
两者都是不可移植的。
为什么有两个不同的函数来获取线程ID?
最佳答案
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()
中使用)。
Both are non portable.
这并不完全正确。 gettid()
不可移植,因为它是 Linux 特定的函数。但是 pthread_self()
是可移植的,只要您不对其表示做任何假设。
例如,以下是不可可移植的。
printf("Thread ID is: %ld", (long) pthread_self());
因为不能保证任何 pthread_self()
都会是某种整数。但是
pthread_t my_tid; //filled elsewhere
pthread_t tid = pthread_self();
if( pthread_equal(my_tid, tid) ) {
/* do stuff */
}
完全便携。
前者不可移植,因为它假设线程 ID 是整数,而后者不是。
Why are there two different functions to get the thread ID?
它们不是获得相同值(value)的两种不同方式。一个 (pthread_self()
由线程库 (pthreads) 提供,而另一个 (gettid()
是操作系统特定的函数。不同的操作系统可能提供不同的接口(interface)/syscall 获取类似于 gettid()
的线程 ID。因此您不能在可移植应用程序中依赖 gettid()
。
关于c - pthread_self() 返回的线程 ID 与调用 gettid(2) 返回的内核线程 ID 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370172/