线程池原理详解及如何用C语言实现线程池
线程数组实际上是在线程池初始化时开辟的一段存放一堆线程tid的空间,在逻辑上形成一个池,里面放置着提前创建的线程;这段空间中包含了正在工作的线程,等待工作的线程(空闲线程),等待被销毁的线程,申明但没有初始化的线程空间; /*工作线程*/ void * threadpool_thread(void *threadpool) { threadpool_t *pool = (threadpool_t *)threadpool; threadpool_task_t task; while (true) { pthread_mutex_lock(&(pool->lock)); /* 无任务则阻塞在 “任务队列不为空” 上,有任务则跳出 */ while ((pool->queue_size == 0) && (!pool->shutdown)) { printf("thread 0x%x is waiting n", (unsigned int)pthread_self()); pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock)); /* 判断是否需要清除线程,自杀功能 */ if (pool->wait_exit_thr_num > 0) { pool->wait_exit_thr_num--; /* 判断线程池中的线程数是否大于最小线程数,是则结束当前线程 */ if (pool->live_thr_num > pool->min_thr_num) { printf("thread 0x%x is exiting n", (unsigned int)pthread_self()); pool->live_thr_num--; pthread_mutex_unlock(&(pool->lock)); pthread_exit(NULL);//结束线程 } } } /* 线程池开关状态 */ if (pool->shutdown) //关闭线程池 { pthread_mutex_unlock(&(pool->lock)); printf("thread 0x%x is exiting n", (unsigned int)pthread_self()); pthread_exit(NULL); //线程自己结束自己 } //否则该线程可以拿出任务 task.function = pool->task_queue[pool->queue_front].function; //出队操作 task.arg = pool->task_queue[pool->queue_front].arg; pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size; //环型结构 pool->queue_size--; //通知可以添加新任务 pthread_cond_broadcast(&(pool->queue_not_full)); //释放线程锁 pthread_mutex_unlock(&(pool->lock)); //执行刚才取出的任务 printf("thread 0x%x start working n", (unsigned int)pthread_self()); pthread_mutex_lock(&(pool->thread_counter)); //锁住忙线程变量 pool->busy_thr_num++; pthread_mutex_unlock(&(pool->thread_counter)); (*(task.function))(task.arg); //执行任务 //任务结束处理 printf("thread 0x%x end working n", (unsigned int)pthread_self()); pthread_mutex_lock(&(pool->thread_counter)); pool->busy_thr_num--; pthread_mutex_unlock(&(pool->thread_counter)); } pthread_exit(NULL); } 三、任务队列 (编辑:应用网_阳江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |