16,601
社区成员
发帖
与我相关
我的任务
分享很少用线程池,最近想写个线程池 查很多示例代码 发现一个很明显的问题:
线程池创建的任务线程:
void* threadPoolWorker(void* arg) {
ThreadPool* pool = (ThreadPool*)arg;
while (1) {
Task* task = dequeue(pool->queue);
if (task == NULL) break; // Exit if no task is available
task->func(task->arg);
free(task);
}
return NULL;
}
task->func(task->arg);是运行队列中等待线程的代码;添加的线程都在这里运行;
销毁函数:
void threadPoolDestroy(ThreadPool* pool) {
// Signal all threads to exit
for (int i = 0; i < pool->numThreads; i++) {
enqueue(pool->queue, NULL); // Send a NULL task as a signal
}
// Wait for all threads to finish
for (int i = 0; i < pool->numThreads; i++) {
pthread_join(pool->threads[i], NULL);
}
}
销毁时会调用pthread_join等待线程结束;然后进一步释放资源;
问题:
如果正在执行的线程是无限循环的;while(true){}这种; 就会一直阻塞在task->func(task->arg); 线程就不会结束;所以pthread_join会一直阻塞;这很明显的一个现象啊为什么网上基本都是这样操作的?
难道线程池只适用于又返回的线程? 如果不是遇到这种无限循环的线程 在实际的项目中是如何处理的?