-
thread pool approach
I have written a demo program below for a thread pool. Do you guys think this is the best approach for initializing a thread pool, using it to do work, and then cancelling it? I have tested this code and it appears to work. I was just wondering if there is a better approach or if I should change anything.
Code:
#define num_workers 5
pthread_t workers[num_workers];
pthread_cond_t available;;
pthread_mutex_t lock;
void* doing_stuff();
void cleanup_handler(void *arg)
{
pthread_mutex_unlock(&lock);
}
int main(int argc, char *argv[])
{
while(1)
{
pthread_cond_init(&available, NULL);
if (pthread_mutex_init(&lock, NULL) != 0)
{
exit(EXIT_FAILURE);
}
system("clear");
printf("\n\n----- Creating threads -----\n\n");
int x;
for(x =0; x<num_workers; x++)
{
pthread_create(&workers[x], NULL, doing_stuff, NULL);
}
sleep(5);
printf("\n\n----- Cancelling threads -----\n\n");
for(x =0; x<num_workers; x++)
{
printf("Canceling thread %lu.\n", workers[x]);
pthread_cancel(workers[x]);
}
for(x =0; x<num_workers; x++)
{
printf("Joining thread %lu.\n", workers[x]);
pthread_join(workers[x], NULL);
}
pthread_mutex_unlock(&lock);
pthread_cond_destroy(&available);
pthread_mutex_destroy(&lock);
sleep(5);
}
return 0;
}
void *doing_stuff()
{
printf("Thread %lu has started.\n", pthread_self());
pthread_cleanup_push(cleanup_handler, NULL);
while(1)
{
pthread_mutex_lock(&lock);
printf("Thread %lu is at wait condition.\n", pthread_self());
pthread_cond_wait(&available, &lock);
/* Perform the work */
pthread_mutex_unlock(&lock);
sleep(5);
}
pthread_cleanup_pop(0);
return NULL;
}
-
Well that's a good start, but it is by no means complete. Now you need to implement the functionality to assign jobs to the thread pool.
-
So this is the proper way to cancel threads and wait for them to finish? I know I have to assign jobs still but I have a better understanding of how that will happen. I just wanted to make sure my handler and cancel methodology was correct. Is it ok if I attempt to join each thread when I cancel to ensure that my main routine waits for all threads to finish?
-
In addition:
- doing_stuff has the wrong signature
- main unlocks 'lock' without having locked it
- don't forget to use a "predicate", associated with the condition, to handle "spurious wakeups" - see the following:
http://www.opengroup.org/onlinepubs/...#tag_03_515_08
- cleanup push/pop isn't used correctly - see the following:
http://www.opengroup.org/onlinepubs/...#tag_03_514_06
http://www.opengroup.org/onlinepubs/...l#tag_02_09_05
- and of course, don't skimp on error checking
gg