1
votes

I want to invoke a different function each time when I make a call to pthread_create. I have four different functions which performs some processing on an array input by user. e.g ascending order, descending order etc. How can I do this inside loop as shown below for one function only?

 for (i = 0; i < num_threads; i++) {
     param[i] = ... ;   // Initialize parameter for thread i
     if ( pthread_create(&tid[i], &attr, worker, & param[i]) != 0 ) {
        printf("Cannot create thread\n");
        exit(1);
     }
 }
1

1 Answers

1
votes

One way of doing it would be to make an array of function pointers, and use i as an index of that array:

void* ascending(void* x)  { ... }
void* descending(void* x) { ... }
void* randomized(void* x) { ... }
void* unchanged(void* x)  { ... }

void* (*start_routines[])(void*) = {ascending, descending, randomized, unchanged};

Now you can do this:

if ( pthread_create(&tid[i], &attr, start_routines[i%4], & param[i]) != 0 ) ...

Thread at index zero will start using start_routines[0], which is ascending. Thread at index one will start using start_routines[1], which is descending, and so on.

Note: If you do not like the "raw" syntax for defining arrays of function pointers, use a typedef to make your code more readable:

typedef void* (*pthread_start_routine)(void*);
pthread_start_routine[] start_routines = {ascending, descending, randomized, unchanged};