I am trying to write a multi-threaded program, the number of threads based on the input on the command line, and therefore I can not hard-code the previously declared threads. Is this the right way to do this?
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 is my result from the changes suggested below. Everything seems to be working 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); }
c pthreads
Brian d
source share