Linux 从单线程应用程序调用pthread_self()

Linux 从单线程应用程序调用pthread_self(),linux,multithreading,process,pthreads,Linux,Multithreading,Process,Pthreads,在Linux上,ps-Lf将在LWP列中显示线程ID,并在NLWP列中显示线程数。任何单线程进程的PID和LWP值都相同 在单线程应用程序上,pthread\u self()应该返回什么?最初我希望它的值应该与执行此调用的进程ID相同,但结果不同。然后我阅读了manpthread\u self和mangettid,了解到pthread\u self()返回的值与gettid()结果不同 因此,我甚至可以信任在非线程环境(进程)中执行的pthread\u self()输出吗?被定义为返回调用线程的

在Linux上,
ps-Lf
将在
LWP
列中显示线程ID,并在
NLWP
列中显示线程数。任何单线程进程的
PID
LWP
值都相同

在单线程应用程序上,
pthread\u self()
应该返回什么?最初我希望它的值应该与执行此调用的进程ID相同,但结果不同。然后我阅读了
manpthread\u self
mangettid
,了解到
pthread\u self()
返回的值与
gettid()
结果不同

因此,我甚至可以信任在非线程环境(进程)中执行的
pthread\u self()
输出吗?

被定义为返回调用线程的ID,而不管程序是否 是多线程还是单线程

正如您所发现的,
pthread_self()
的返回值与Linux中的LWP(
gettid
)不同,因此它在进程之外没有任何意义
pthread\u t
不透明字体。相关的:

它的实用性非常有限,因为在单线程程序中,
pthread\u t
没有多少实际用途。例如,您可以在
pthread_setschedparam
中使用


但是如果您询问是否在单线程程序中返回任何有效值,那么答案是肯定的。

如果您在多线程程序中信任它,为什么不在单线程程序中?;-)@P.P好的,但是我如何解释pthread\u t值呢?它被故意设置为不透明的,并且是特定于实现的,例如,它可以是整数,也可以被包装在
struct
等中。这是否意味着如果我需要线程ID的整数表示,我应该只使用
getId
?你无论如何都不会解释它-这就是它不透明的原因。
pthread\u t
是由pthreads库分配的,在进程之外,它没有任何有用的意义。把它想象成你给线程起的名字,比如给线程起的“master”、“worker”、“timer”等等。如果您需要整数表示,您可以自己指定一个(例如,将每个
pthread\u t
映射到一个int或包装到一个struct:
struct mythreads{pthread\u t tid;int tid;}
)。当然,您也可以使用
gettid
,但这不太便于移植,因为
gettid
是特定于Linux的(pthreads库可以在任何POSIX系统上使用)。