stack allocation of pthread_mutex_t with initializer

Carlos O'Donell carlos@systemhalted.org
Fri Aug 9 19:45:00 GMT 2013


On Fri, Aug 9, 2013 at 1:19 PM, Godmar Back <godmar@gmail.com> wrote:
> Is it required to call pthread_mutex_destroy on mutexes allocated as
> automatic variables?

(1) static vs. automatic?

You are not allowed to use PTHREAD_MUTEX_INITIALIZER with non-static allocation.

http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html
~~~
In cases where default mutex attributes are appropriate, the macro
PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are
***statically*** allocated. The effect shall be equivalent to dynamic
initialization by a call to pthread_mutex_init() with parameter attr
specified as NULL, except that no error checks are performed.
~~~

It's problematic because present forms of initialization might
actually invoke a function that is not thread safe (or is not an
atomic operation). Thus two threads racing to use the new mutex might
actually result in undefined behaviour (similar things can happen in
C++).

(2) Call pthread_mutex_destroy?

* Required?

No. The standard makes no hard requirement that pthread_mutex_destroy
must be called at all.

* In general?

Yes, it's good practice. Using the static initializer is equivalent to
having called pthread_mutex_init, and in order to claim any consumed
resources you must call pthread_mutex_destroy.

* In glibc?

No, but it might change in the future, so you must not rely on this.

For the good of the library it must be allowed to change within the
semantic guarantees of the standard.

At present we don't allocate an additional resources or free any
additional resources.

Cheers,
Carlos.



More information about the Libc-help mailing list