【问题标题】:call pthread_self() from a single-threaded application从单线程应用程序调用 pthread_self()
【发布时间】:2020-08-12 19:01:17
【问题描述】:

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

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

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

【问题讨论】:

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

标签: linux multithreading process pthreads


【解决方案1】:

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 中使用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多