c - Pass argument to multiple threads -


new c, reading here how pass argument thread. if argument needed passed multiple threads? where/how should use free()? say:

void *foo(void *i) {     int = *((int *) i);       while(1){         printf("foo running \n");         sleep(1);     } }  void *bar(void *i) {     int = *((int *) i);        while(1){         printf("bar running \n");         sleep(1);     } }  int main() {     pthread_t threads[2];     int i;     (i = 0; < 2; i++ ) {         int *arg = malloc(sizeof(*arg));         if ( arg == null ) {             fprintf(stderr, "couldn't allocate memory thread arg.\n");             exit(1);         }         *arg = i;         pthread_create(&threads[0], null, foo, arg);         pthread_create(&threads[1], null, bar, arg);     }     (i = 0; < 2; i++){         pthread_join(threads[i],null);     }     return 0; } 

is calling free(arg); in main after spawning threads same thing / safe?

if threads needs exact same argument, , not modifying argument, there's no need allocate dynamically @ all, instead declare variable @ function scope in main function. if there's no dynamic allocation, there's no need free it.

on other hand if need separate arguments in loop do, need keep track of arguments, example using array:

// rest of program...  #define number_of_iterations 2  int main(void) {     int args[number_of_iterations];     pthread_t threads[number_of_iterations][2];      // create threads     (unsigned = 0; < number_of_iterations; ++i)     {         args[i] = i;         pthread_create(&threads[i][0], null, foo, &args[i]);         pthread_create(&threads[i][1], null, bar, &args[i]);     }      // wait threads finish     (unsigned = 0; < number_of_iterations; ++i)     {         pthread_join(threads[i][0]);         pthread_join(threads[i][1]);     }      return 0; } 

the program above solves problem have, when create total of 4 threads join two.


Comments