我有一个要下载的大文件的URL列表(例如压缩档案),我想处理这些文件(例如解压缩档案)。在
下载和处理都需要很长的时间,而且处理在磁盘IO上很繁重,所以我希望一次只运行一个。由于这两个任务占用的时间差不多,并且不会争夺相同的资源,所以我希望在处理最后一个任务时下载下一个文件。在
这是producer-consumer problem的变体。在
这种情况类似于reading and processing images或{a3},但我的下载器调用(还)不可选择,所以我无法使用多处理,而且两个任务的时间几乎相同。在
下面是一个虚拟示例,其中下载和处理都被阻塞:
import time
import posixpath
def download(urls):
for url in urls:
time.sleep(3) # this is the download (more like 1000s)
yield posixpath.basename(url)
def process(fname):
time.sleep(2) # this is the processing part (more like 600s)
urls = ['a', 'b', 'c']
for fname in download(urls):
process(fname)
print(fname)
如何使这两个任务同时进行?我可以使用yield
或yield from
in a smart way,也许与^{
我只需使用
threading.Thread(target=process, args=(fname,))
并启动一个新线程进行处理。在但在此之前,结束最后一个处理线程:
见https://docs.python.org/3/library/threading.html
一年后,我们实际上在使用python3的^{} 和{a2}。在
相关问题 更多 >
编程相关推荐