Results 1 to 1 of 1
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, ...
- 11-04-2009 #1Just Joined!
- Join Date
- Oct 2009
- Posts
- 7
Best 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; }


Reply With Quote
