KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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
Tags (comma-separated)
Save Edits
Cancel