面试题答案
一键面试实现思路
- 记录线程空闲时间:每个线程在进入空闲状态时,记录当前时间。
- 定时检查:使用一个管理线程,定时检查所有线程的空闲时间。
- 释放空闲线程:如果某个线程的空闲时间超过设定的阈值,将其释放。
- 动态创建线程:当任务队列中有新任务且当前活动线程数小于设定的最大线程数时,创建新线程。
关键代码片段
- 线程结构体定义
typedef struct {
pthread_t tid;
int is_busy;
time_t idle_start_time;
} Thread;
- 管理线程检查空闲线程
void* monitor_thread(void* arg) {
ThreadPool* pool = (ThreadPool*)arg;
while (1) {
sleep(CHECK_INTERVAL);
pthread_mutex_lock(&pool->mutex);
for (int i = 0; i < pool->max_threads; i++) {
if (!pool->threads[i].is_busy && (time(NULL) - pool->threads[i].idle_start_time > IDLE_THRESHOLD)) {
pool->threads[i].is_busy = 1;
pthread_cancel(pool->threads[i].tid);
pool->active_threads--;
}
}
pthread_mutex_unlock(&pool->mutex);
}
return NULL;
}
- 任务处理线程
void* worker_thread(void* arg) {
ThreadPool* pool = (ThreadPool*)arg;
while (1) {
Task task;
pthread_mutex_lock(&pool->mutex);
while (pool->task_queue.size == 0 &&!pool->shutdown) {
pthread_cond_wait(&pool->cond, &pool->mutex);
}
if (pool->shutdown && pool->task_queue.size == 0) {
pthread_mutex_unlock(&pool->mutex);
pthread_exit(NULL);
}
task = pool->task_queue.tasks[pool->task_queue.head];
pool->task_queue.head = (pool->task_queue.head + 1) % pool->task_queue.capacity;
pool->task_queue.size--;
pool->threads[pool->active_threads].is_busy = 1;
pool->active_threads++;
pthread_mutex_unlock(&pool->mutex);
(task.func)(task.arg);
pthread_mutex_lock(&pool->mutex);
pool->threads[pool->active_threads - 1].is_busy = 0;
pool->threads[pool->active_threads - 1].idle_start_time = time(NULL);
pool->active_threads--;
pthread_mutex_unlock(&pool->mutex);
}
return NULL;
}
- 添加任务时动态创建线程
void add_task(ThreadPool* pool, void* (*func)(void*), void* arg) {
pthread_mutex_lock(&pool->mutex);
while (pool->task_queue.size == pool->task_queue.capacity &&!pool->shutdown) {
pthread_cond_wait(&pool->not_full, &pool->mutex);
}
if (pool->shutdown) {
pthread_mutex_unlock(&pool->mutex);
return;
}
pool->task_queue.tasks[pool->task_queue.tail] = (Task){func, arg};
pool->task_queue.tail = (pool->task_queue.tail + 1) % pool->task_queue.capacity;
pool->task_queue.size++;
if (pool->active_threads < pool->max_threads && pool->task_queue.size > pool->min_idle_threshold) {
int i;
for (i = 0; i < pool->max_threads; i++) {
if (!pool->threads[i].is_busy) {
break;
}
}
if (i == pool->max_threads) {
if (pthread_create(&pool->threads[pool->max_threads].tid, NULL, worker_thread, pool) != 0) {
// 处理创建线程失败
}
pool->max_threads++;
}
}
pthread_cond_signal(&pool->not_empty);
pthread_mutex_unlock(&pool->mutex);
}
以上代码为简化示意,实际使用中可能需要更多错误处理和完善。