从单线程应用程序调用pthread_self

问题描述

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

pthread_self()在单线程应用程序上应该返回什么?最初,我期望其值应与执行此调用的进程ID相同,但结果不同。然后,我读了man pthread_selfman gettid,得知pthread_self()返回的值与gettid()结果不同。

那么我什至可以相信在非线程环境(进程)中执行的pthread_self()输出吗?

解决方法

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

您发现,pthread_self()的返回值与Linux中的LWP(gettid)不同,因此它在流程之外没有任何意义; pthread_t是 不透明的类型。相关:The thread ID returned by pthread_self() is not the same thing as the kernel thread ID returned by a call to gettid(2)

它的实用程序非常有限,因为在单线程程序中pthread_t并没有太多实际用途。例如,您可以在pthread_setschedparam中使用。

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