7

I would like to build a dynamic malloced array of pthread_mutex that will grow over time (adding more mutexes). My question is whether they will still work if the array gets moved with realloc(). My concern is that pthread_mutex_init() might somehow set up internal information that depends on the address of the mutex at that moment.

To be more specific, here is a toy snippet that shows the issue:

pthread_mutex_t *my_mutexes = (pthread_mutex_t *) malloc (sizeof(pthread_mutex_t));
pthread_mutex_init (my_mutexes, NULL);
my_mutexes = (pthread_mutex_t *) realloc (my_mutexes, 2*sizeof(pthread_mutex_t));
/* does my_mutexes[0] still work at this point? */

I suppose the answer in all such cases is "if it's not expressly allowed, assume not" but I wanted to get the sage advice here. If the conclusion is not to do this, then I wonder how, in general, I might create a growing list of mutexes.

idmean
  • 14,540
  • 9
  • 54
  • 83
pidloop
  • 103
  • 8

1 Answers1

6

It's not safe to move mutexes. Some mutex implementations on Linux, for example, use the futex system call which specifically waits on the address of the mutex.

If it needs to grow dynamically, I'd suggest using a master array of pthread_mutex_t pointers and a mutex for that master list. When you grow the array, you will just be moving the list of pointers rather than the mutexes themselves. The mutexes can be allocated with plain malloc.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Great idea that neatly avoids the issue entirely, thanks very much. – pidloop Jan 31 '13 at 18:16
  • Is the issue with `futex` only relevant if you're trying to move a `pthread_mutex_t` that's currently locked? Or would moving break something even if the mutex was unlocked at the time? – Jack O'Connor Jun 10 '21 at 19:59
  • Here's some more discussion of my question above: https://twitter.com/m_ou_se/status/1403413967846977538 – Jack O'Connor Jun 11 '21 at 21:13