Can pthread_mutex_t move in memory?

I would like to create a dynamic malloced pthread_mutex array that will grow over time (adding additional mutexes). My question is whether they will work if the array is moved using realloc (). My concern is that pthread_mutex_init () might somehow tweak the internal information, which depends on the mutex address at that moment.

To be more specific, here is a fragment of a toy that shows the problem:

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 that the answer in all such cases is "if this is not explicitly permitted, do not accept", but I wanted to get the advice of the sage here. If the conclusion is not for this, then I wonder how, in the general case, I could create a growing list of mutexes.

+4
source share
1 answer

You cannot safely move mutexes. For example, some Linux mutex implementations use the futex system call, which specifically waits for the mutex address.

If it should grow dynamically, I would suggest using the main array of pointers pthread_mutex_t and mutex for this main list. When you grow an array, you simply move the list of pointers, not the mutexes themselves. Mutexes can be allocated using a simple malloc .

+2
source

All Articles