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

call pthread_self() from a single-threaded application

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

在单线程应用程序上 pthread_self() return 应该做什么?最初我期望它的值应该与进程 ID 相同,执行此调用,但结果不同。然后我阅读 man pthread_selfman gettid 并了解到 pthread_self() 编辑的值 return 与 gettid() 结果不同。

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

pthread_self 定义为 return 调用线程的 ID,无论程序是否 是 multi-threaded 或 single-threaded.

如您所见,pthread_self() 的 return 值与 Linux (gettid) 中的 LWP 不同,因此它没有过程之外的任何意义; pthread_t 是 不透明类型。相关:

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

但是如果你问 return 在 single-threaded 程序中是否有任何有效值,那么答案是肯定的。