No, you don't have to create them dynamically. You can use a static array, you just have to get them all set up before you use them. You can do:
#define NUM_THREADS 5
static pthread_mutex_t mutexes[NUM_THREADS] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
which is prone to errors if you ever change NUM_THREADS
, though that can be fixed with something like:
static pthread_mutex_t mutexes[] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
#define NUM_THREADS (sizeof(mutexes)/sizeof(*mutexes))
Alternatively, you can do it with code, such as:
#define NUM_THREADS 5
static pthread_mutex_t mutexes[NUM_THREADS];
// Other stuff
int main (void) {
for (int i = 0; i < NUM_THREADS; i++)
pthread_mutex_init(&mutexes[i], NULL);
// Now you can use them safely.
return 0;
}
In all those cases, they're correctly set up before you try to use them. In fact, I'd do it well before you do any threading stuff but that's just me being paranoid.