void *thread_routine(void *arg) { struct timespec abstime; int timeout; printf("thread 0x%0x is starting\n",(int)pthread_self()); threadpool_t *pool = (threadpool_t *)arg; while(1) { timeout = 0; condition_lock(&pool -> ready); pool -> idle++; //等待队列有任务到来或者线程池销毁的通知 while(pool -> first == NULL && !pool -> quit) { printf("thread 0x%0x is waiting\n",(int)pthread_self()); clock_gettime(CLOCK_REALTIME,&abstime); abstime.tv_sec += 2; int status=condition_timewait(&pool -> ready,&abstime); if(status == ETIMEDOUT) { printf("thread 0x%0x is wait timed out\n",(int)pthread_self()); timeout = 1; break; } } //等到到条件,处于工作状态 pool -> idle--; if(pool -> first != NULL) { task_t *t = pool -> first; pool -> first = t -> next; //需要先解锁,以便添加新任务。其他消费者线程能够进入等待任务。 condition_unlock(&pool -> ready); t -> run(t->arg); free(t); condition_lock(&pool -> ready); } //等待线程池销毁的通知 if(pool -> quit && pool ->first == NULL) { pool -> counter--; if(pool->counter == 0) { condition_signal(&pool -> ready); } condition_unlock(&pool->ready); //跳出循环之前要记得解锁 break; } if(timeout &&pool -> first ==NULL) { pool -> counter--; condition_unlock(&pool->ready); //跳出循环之前要记得解锁 break; } condition_unlock(&pool -> ready); } printf("thread 0x%0x is exiting\n",(int)pthread_self()); return NULL; }
void* thread_routine(void* arg) { struct timespec abstime; int timeout; printf("thread 0x%x is starting ...\n", (int)pthread_self()); threadpool_t* pool = (threadpool_t*)arg; while(1) { timeout = 0; condition_lock(&pool->ready); pool->idle++; while(pool->first == NULL && !pool->quit) { printf("thread 0x%x is waiting ...\n", (int)pthread_self()); clock_gettime(CLOCK_REALTIME, &abstime); abstime.tv_sec += 2; int status = condition_timewait(&pool->ready, &abstime); if(status == ETIMEDOUT) { printf("thread 0x%x is wait timed out ...\n", (int)pthread_self()); timeout = 1; break; } } pool->idle--; if(pool->first != NULL) { task_t* t = pool->first; pool->first = t->next; condition_unlock(&pool->ready); t->run(t->arg); free(t); condition_lock(&pool->ready); } if(pool->quit && pool->first == NULL) { if(--pool->counter == 0) condition_signal(&pool->ready); condition_unlock(&pool->ready); break; } if(timeout && pool->first == NULL) { pool->counter--; condition_unlock(&pool->ready); break; } condition_unlock(&pool->ready); } printf("thread 0x%x is exiting ...\n", (int)pthread_self()); return NULL; }