Python主线程等待子线程完成
问题背景
最近开发的一个小脚本,主要是用来对文件进行翻译,由于是用http请求的方式调用机翻的API,耗时大,任务多,所以运用多线程技术。先通过对xml解析,在子线程中进行翻译,最后一次性写入文件。发现子线程还没有完全结束的时候,主线程已经结束。
代码分析
通过学习,一定会调用线程的join函数。join函数的作用就是阻塞调用的线程,等待子线程全部完成之后,再启动调用的线程以下是源码注释:
This blocks the calling thread until the thread whose join() method is
called terminates – either normally or through an unhandled exception
or until the optional timeout occurs.
可以看到,调用线程(调用子线程的线程)会等待子线程的结束。
于是,我就去试了一下。在工作线程中,调用join函数
# task是任务队列,接收thread子类,也就是工作线程
while len(self.tasks)>0 :
job = self.task.pop();
job.start()
job.join()
再次启动脚本,并没有什么用。由于对线程池的熟练度不够。仔细检查代码,理解了上述注释之后,就明白了。请先看线程池的代码:
# 这个代码是网上一位大佬的java实现,自己转python,但是具体url历史记录找不到了,感谢大佬
import queue
import string
import threading
import worker
class threadPool:
"""
自定义线程池
成员变量
1、任务队列
2、当前线程数量
3、核心线程数量
4、最大线程数量
5、任务队列的长度
成员方法
1、提交任务
2、执行任务
"""
tasks = []
threadnum = 0
def __init__(self, coresize, maxsize, worksize):
self.coresize = coresize
self.maxsize = maxsize
self.worksize = worksize
def submit(self, thread=threading.Thread):
if len(self.tasks) >= self.worksize:
print("任务" + thread.name + "丢弃")
else:
self.tasks.append(thread)
self.execthread(thread)
def execthread(self, thread):
if self.threadnum < self.coresize:
item = worker.worker("核心线程" + str(self.threadnum), self.tasks)
item.start()
# item.join()
self.threadnum += 1
elif self.threadnum < self.maxsize:
item = worker.worker("非核心线程" + str(self.threadnum), self.tasks)
item.start()
# item.join()
self.threadnum += 1
else:
print("被缓存")
主线程通过pool的submit函数提交任务之后,exec执行部分,join被注释调,主线程就不会等待线程池执行完成,所以要在这里加上join函数,让主线程等待线程池,线程池等待工作线程完成,这样一个流程。
总结
至此,这个多线程的小问题就解决了。也不是很小吧,只是一开始确实没什么思路,经过查找资料和思考才能解决。希望各位同学少出bug,多挣钱。
文档如有错误,希望各位大佬指出。共同完成高质量的文档。