为什么pthread_t是不透明类型?

问题描述 投票:3回答:2

[SO上的帖子表明pthread_t是不透明的类型,不是数字,当然不是线程索引,您不应该直接比较pthread_t的类,等等。

问题:

  1. 为什么?是否真的有意要为没有数字ID的系统提供支持?当pthread_t实现只是

    typedef unsigned long int pthread_t;
    

  2. 怎么样?上一行之前有一条评论,所以实际上是

    /* Thread identifiers. The structure of the attribute type is not
       exposed on purpose.  */
    typedef unsigned long int pthread_t;
    

    pthreadtypes.h中是什么意思?什么属性类型?这不是对某些全局线程表的索引吗?

c multithreading pthreads
2个回答
3
投票

是否真的有意图支持没有数字ID的系统?

有多种类型可以用作数字线程标识符。例如,在资源有限的系统上,可以使用8位线程标识符代替unsigned long

属性类型的结构不是故意公开的。

对于pthread_t定义,注释为不是,但对于pthread_attr_t定义,以下一行:

typedef union
{
  char __size[__SIZEOF_PTHREAD_ATTR_T];
  long int __align;
} pthread_attr_t;

评论指出,char __size[__SIZEOF_PTHREAD_ATTR_T]用于隐藏实际struct的内容。

不是[pthread_t]到某个全局线程表的索引吗?

不一定是。隐藏实际类型的事实允许实现者使用他希望的任何类型,包括指针或struct。使用struct可使实现者避免在其库的代码中使用全局线程表(不过,操作系统可能会保留该表)。


4
投票

POSIX标准允许pthread_t更为复杂(例如结构)。 See this previous question,尤其是@ james-mcnellis的答案。货币报价:

应用了IEEE Std 1003.1-2001 / Cor 2-2004,项目XBD / TC2 / D6 / 26,添加pthread_t到不需要算术的类型列表类型,因此允许将pthread_t定义为结构。

UPDATE:以下是一些更复杂的pthread_t定义的示例:

[这是Win32的pthreads库中使用的pthread_t结构的古老(2007)证明:https://sourceware.org/ml/pthreads-win32/2007/msg00056.html

© www.soinside.com 2019 - 2024. All rights reserved.