Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and in what sense is pthread_t an opaque type?

Posts here on SO suggest that pthread_t is an opaque type, not a number, certainly not a thread index, that you shouldn't directly compare pthread_t's, etc. etc.

Questions:

  1. Why? Is there really the intent to support systems with no numeric IDs for threads? When the pthread_t implementation is simply

    typedef unsigned long int pthread_t;
    

    ?

  2. How? There's a comment before the above line, so it's actually

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

    in pthreadtypes.h what does that mean? What attribute type? Isn't this an index into some global table of threads?

like image 416
einpoklum Avatar asked Oct 22 '15 16:10

einpoklum


2 Answers

The POSIX standard allows pthread_t to be something more complex (such as a structure). See this previous question, especially the answer by @james-mcnellis. Money quote:

IEEE Std 1003.1-2001/Cor 2-2004, item XBD/TC2/D6/26 is applied, adding pthread_t to the list of types that are not required to be arithmetic types, thus allowing pthread_t to be defined as a structure.

UPDATE: Here are a few examples of more complex pthread_t definitions:

  • https://github.com/JoakimSoderberg/pthreads-win32/blob/master/pthread.h
  • http://www.mit.edu/afs.new/sipb/project/pthreads/include/pthread.h
  • http://svn.gna.org/svn/xenomai/trunk/include/posix/pthread.h

And here is an ancient (2007) justification of the pthread_t structure used in the pthreads library for Win32: https://sourceware.org/ml/pthreads-win32/2007/msg00056.html

like image 74
keithmo Avatar answered Sep 23 '22 13:09

keithmo


Is there really the intent to support systems with no numeric IDs for threads?

There are different types that could serve as numeric thread identifier. For example, on systems with limited resources an 8-bit thread identifier could be used instead of unsigned long.

The structure of the attribute type is not exposed on purpose.

The comment is not for pthread_t definition, but for the pthread_attr_t definition one line below:

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

The comment states that char __size[__SIZEOF_PTHREAD_ATTR_T] is used in order to hide the content of the actual struct.

Isn't [pthread_t] an index into some global table of threads?

It does not have to be. The fact that the actual type is hidden allows an implementer to use any type that he wishes, including a pointer or a struct. Using a struct lets the implementer avoid using a global table of threads in the code of his library (OS would probably keep such table, though).

like image 35
Sergey Kalinichenko Avatar answered Sep 23 '22 13:09

Sergey Kalinichenko