Skip to content

Commit

Permalink
use signaling instead of polling in thpool_wait
Browse files Browse the repository at this point in the history
  • Loading branch information
dweymouth committed Dec 2, 2015
1 parent c606e5a commit 49f19b4
Showing 1 changed file with 8 additions and 39 deletions.
47 changes: 8 additions & 39 deletions thpool.c
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ typedef struct thpool_{
volatile int num_threads_alive; /* threads currently alive */
volatile int num_threads_working; /* threads currently working */
pthread_mutex_t thcount_lock; /* used for thread count etc */
pthread_cond_t threads_all_idle; /* signal to thpool_wait */
jobqueue* jobqueue_p; /* pointer to the job queue */
} thpool_;

Expand Down Expand Up @@ -192,46 +193,11 @@ int thpool_add_work(thpool_* thpool_p, void *(*function_p)(void*), void* arg_p){

/* Wait until all jobs have finished */
void thpool_wait(thpool_* thpool_p){

/* Continuous polling */
double timeout = 1.0;
time_t start, end;
double tpassed = 0.0;
time (&start);
while (tpassed < timeout &&
(thpool_p->jobqueue_p->len || thpool_p->num_threads_working))
{
time (&end);
tpassed = difftime(end,start);
}

/* Exponential polling */
long init_nano = 1; /* MUST be above 0 */
long new_nano;
double multiplier = 1.01;
int max_secs = 20;

struct timespec polling_interval;
polling_interval.tv_sec = 0;
polling_interval.tv_nsec = init_nano;

while (thpool_p->jobqueue_p->len || thpool_p->num_threads_working)
{
nanosleep(&polling_interval, NULL);
if ( polling_interval.tv_sec < max_secs ){
new_nano = CEIL(polling_interval.tv_nsec * multiplier);
polling_interval.tv_nsec = new_nano % MAX_NANOSEC;
if ( new_nano > MAX_NANOSEC ) {
polling_interval.tv_sec ++;
}
}
else break;
}

/* Fall back to max polling */
while (thpool_p->jobqueue_p->len || thpool_p->num_threads_working){
sleep(max_secs);
pthread_mutex_lock(&thpool_p->thcount_lock);
while (thpool_p->jobqueue_p->len || thpool_p->num_threads_working) {
pthread_cond_wait(&thpool_p->threads_all_idle, &thpool_p->thcount_lock);
}
pthread_mutex_unlock(&thpool_p->thcount_lock);
}


Expand Down Expand Up @@ -382,6 +348,9 @@ static void* thread_do(struct thread* thread_p){

pthread_mutex_lock(&thpool_p->thcount_lock);
thpool_p->num_threads_working--;
if (!thpool_p->num_threads_working) {
pthread_cond_signal(&thpool_p->threads_all_idle);
}
pthread_mutex_unlock(&thpool_p->thcount_lock);

}
Expand Down

0 comments on commit 49f19b4

Please sign in to comment.