Old question, but I faced the same problem today, and I decided not to follow this path.
My application was really about performance, so I chose to have this array of int
s declared statically.
Since I don't know a lot of applications where your pthread_join
/ pthread_cancel
is in another scope than your pthread_create
, I chose this way :
#define NB_THREADS 4
void *job(void *_i) {
unsigned int i = *((unsigned int *) _i);
}
int main () {
unsigned int ints[NB_THREADS];
pthread_t threads[NB_THREADS];
for (unsigned int i = 0; i < NB_THREADS; ++i) {
ints[i] = i;
pthread_create(&threads[i], NULL, job, &ints[i]);
}
}
I find it more elegant, more efficient, and you don't have to worry about freeing since it only lives in this scope.
error: invalid conversion from ‘void*’ to ‘int*’
at this line :int *arg = malloc(sizeof(*arg));
. You should put (int *) before malloc. – Accent