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
If you're trying to write a multithreaded program, but don't understand how to allocate a dynamically sized data structure, you may be doing things wrong.
Learn to walk before you run.
Consider using an easier language, and avoiding the use of (explicit) threads.
Threads are very difficult to use correctly; dynamically sized arrays are very easy to achieve (even fairly easy in C)
The first for
loop is not valid C, and I'm not sure what you want it to do. Just remove it and the rest of the code looks ok, aside from the incorrect cast on foobar_function
. The cast should be:
(void *(*)(void *))foobar_function
but unless the type is already this, or something very close, your program probably has undefined behavior. It would be better to fix the function signature so no cast is needed.
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.