0

Imagine I've got a pthread mutex somewhere on the heap.

pthread_mutex_t *mutex;

Should I always destroy like this before freeing the memory?

pthread_mutex_destroy(mutex);
free(mutex);

Or should I simply invoke free() without concerning myself with the destroy? From its man page it looks like it switches the mutex internal state back to uninitialized, so is it really necessary when I'm going to free the memory anyway?

Riccardo T.
  • 8,907
  • 5
  • 38
  • 78

1 Answers1

3

The thing about pthread_mutex_destroy() is that it returns an error code, which is very useful to confirm the state of the mutex in question. According to the man page:

The pthread_mutex_destroy() function may fail if:

EBUSY The implementation has detected an attempt to destroy the object referenced by mutex while it is locked or referenced (for example, while being used in a pthread_cond_timedwait() or pthread_cond_wait()) by another thread.

EINVAL The value specified by mutex is invalid.

So, if you are already absolutely certain that the mutex is suitable for release, then you can just call free(mutex). If you are just assuming that it is suitable, then strangeness is likely to ensue.

Mark Benningfield
  • 2,800
  • 9
  • 31
  • 31
  • 1
    *then you can just call free(mutex)* No, you can't - failing to call `pthread_mutex_destroy()` means resources may be leaked. See [this answer](https://stackoverflow.com/a/54300838/4756299) on the question this has been marked a dupe of. – Andrew Henle Jan 11 '21 at 12:12
  • Thanks for the extra concurrency concerns about being able or not to destroy/deallocate it, but @AndrewHenle is right: on that other anser it is demonstrated that memory leaks might actually occurr when not invoking `pthread_mutex_destroy()`. – Riccardo T. Jan 11 '21 at 12:22
  • @AndrewHenle: Good point. It certainly reinforces the requirement of absolute certainty about the state of the mutex in question. – Mark Benningfield Jan 11 '21 at 12:22
  • `EBUSY` is implementation specific. Not all linux distributions appear to support it. In example, this is taken from the CentOS man pages: _"It shall be safe to destroy an initialized mutex that is unlocked. Attempting to destroy a locked mutex results in undefined behavior."_ – Riccardo T. Jan 11 '21 at 13:53
  • @RiccardoT.: Yes, and according to The Open Group POSIX [specs](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_destroy.html#), the `pthread_mutex_destroy()` function returns an error code on failure, but _does not_ specifiy any error codes. So one should _definitely_ check the references for the specific implementation. – Mark Benningfield Jan 11 '21 at 14:04