c - pthread_self() 返回的线程 ID 与调用 gettid(2) 返回的内核线程 ID 不同

标签 c linux multithreading pthreads

该引用来自 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/

相关文章:

c - 像这样的 C "spec"文件是如何创建的?

linux - 内存保护键 内存重新排序

json - 使用linux服务器获取键值对

java - 为什么需要 "Storing a reference to it into a final field"和 "of a properly constructed object"才能安全地发布对象?

.net - 为什么必须有一个委托(delegate)来桥接线程及其方法?

C - 在 2D 数组扫雷中循环到 "plant mines"不起作用

iphone - 在 Objective C (Cocoa) 线程中运行 C 代码(适用于 iOS)

c - roll() 函数导致的未定义行为(使用 C)

linux - 无法启动梯形图服务

c - 并行应用程序具有随机行为