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 doing it?
int threads = 5; // (dynamic, not hard-coded)
int i = 0;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
pthread_t foobar;
thread[i] = foobar; // will this cause a conflict?
}
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
Here’s my result from modifications suggested below. Seems to work just fine.
int threads = 5;
int i;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
// pthread_join(thread[i], NULL); // don't actually want this here :)
}
sleep(1); // main() will probably finish before your threads do,
free(thread); // so we'll sleep for illustrative purposes
What’s in the first cycle? Does it set the array elements to uninitialized value?
So i think that’s what you need:
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.