PoVa
PoVa

Reputation: 1043

Pthread attribute usage

I have a couple of questions regarding pthread attributes that I could not find answers to elsewhere.

  1. If I create an attribute (thread/mutex), can I free it right after assigning it to a thread/mutex, or do I have to keep it until the thread finishes?
  2. Is it safe to reuse attributes (thread/mutex) on multiple threads/mutexes?

Upvotes: 4

Views: 1509

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754810

If you read the POSIX specification for pthread_mutexattr_init(), it says:

After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes.

Similarly, though not quite so clearly, the specification for pthread_attr_init() says:

The resulting attributes object (possibly modified by setting individual attribute values) when used by pthread_create() defines the attributes of the thread created. A single attributes object can be used in multiple simultaneous calls to pthread_create().

And the specification of pthread_create() says:

The pthread_create() function shall create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes shall be used. If the attributes specified by attr are modified later, the thread's attributes shall not be affected.

I think those quotes mean that the answers are:

  1. Yes, you may destroy the attribute object when it is convenient. In effect, the POSIX calls make a copy of the attributes.

  2. Yes, it is safe to reuse attributes.

Upvotes: 4

Related Questions