I\'m trying to write a multi-threaded program, the number of threads based on command-line input, and so I can\'t hard-code pre-declared threads. Is this a valid way of doin
What's in the first cycle? Does it set the array elements to uninitialized value?
So i think that's what you need:
int threads = 5, i = 0, ret = -1;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
It spawns threads threads, starting foobar_function in each. And you have (if everything goes well:)) their ids in thread array. So for example you can cancel second thread by calling pthread_cancel(thread[1]) etc.