Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when pthread_attr_t is not NULL?

All parameters for pthread_create from POSIX threads are pretty straightforward to understand, except pthread_attr_t. What is pthread_attr_t for, how, and when it is supposed to be not initialized by NULL?

I went through the Linux man page. The description I found about pthread_attr_t is:

  • Syntax:

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void*),void *arg);
    
  • Explanation:

    The attr argument points to a pthread_attr_t structure whose contents
    are used at thread creation time to determine attributes for the new
    thread; this structure is initialized using pthread_attr_init(3) and
    related functions.  If attr is NULL, then the thread is created with
    default attributes.
    

Which is very unclear. I also googled all over the internet, and no clear explanation to be found anywhere either. So, when pthread_attr_t is not NULL?

Can someone please shed some light about that? All comments and feedback are highly appreciated.

like image 892
Jessica Cohen Avatar asked Mar 25 '17 22:03

Jessica Cohen


1 Answers

You can use it to created a detached (non-joinable) thread, or to set the thread's stack size to a non-default value, amongst other attributes.

See the POSIX specifications for:

  • pthread_attr_init()
  • pthread_attr_setdetachstate()
  • pthread_attr_setguardsize()
  • pthread_attr_setinheritsched()
  • pthread_attr_setschedparam()
  • pthread_attr_setschedpolicy()
  • pthread_attr_setscope()
  • pthread_attr_setstack()
  • pthread_attr_setstacksize()

(There are two functions per URL — pthread_attr_destroy() and 'get' analogues to the 'set' functions.)

Most often, you don't need to modify these. Passing a NULL pointer to pthread_create() is equivalent to using a default set of attributes — which is what pthread_attr_init() creates for you. You can change the attributes that you wish to change in the pthread_attr_t object via the functions and then pass that modified object to pthread_create() instead.

Another thing that there is no apparent justification either, is the first argument from pthread_create on pthread_t data type definition.

All the POSIX thread types are opaque — that was a deliberate design decision by the POSIX committees. You can't poke around inside the type portably. This makes it easier for the implementation — you can only do what the functions allow you to do. Ultimately, it simplifies life for the programmers (users) too; you don't get tricked into using internal knowledge of the POSIX implementation that won't migrate to other systems.

like image 94
Jonathan Leffler Avatar answered Sep 30 '22 00:09

Jonathan Leffler