I want to initialize a large number of mutexes for synchronizing threads.
The following syntax causes a build error "Expected expression" inside the loop:
pthread_mutex_t *mtxs = malloc(MAX * sizeof(pthread_mutex_t));
for (size_t i=0; i<MAX; i++) {
mtxs[i] = PTHREAD_MUTEX_INITIALIZER;
}
I also tried using pointer arithmetic instead of an array:
*(mtxs+i) = PTHREAD_MUTEX_INITIALIZER;
but get the same error.
However, the following code, using 2 steps instead of 1 for the init, works fine:
pthread_mutex_t *mtxs = malloc(MAX * sizeof(pthread_mutex_t));
for (size_t i=0; i<MAX; i++) {
pthread_mutex_t tmp = PTHREAD_MUTEX_INITIALIZER;
mtxs[i] = tmp;
}
Why does the '1-step' init cause a build error, but '2-step' works fine?
And is there a different syntax for a 1-step init that would work?