【发布时间】:2022-01-25 22:07:00
【问题描述】:
我有超过 10000 个文件需要打开,其中一些我需要删除部分数据 试图用线程池来做,但从它开始我认为它不起作用
from multiprocessing.pool import ThreadPool
def readwrite(file):
with open(file,'rb') as f:
#check something
#if check something is True
#else return
with open(new_file,'wb') as f:
with open(file,'rb') as g:
#here i write only the lines i need from the first file
pool = ThreadPool(40)
for file in files:
pool.apply_async(readwrite,(file,))
【问题讨论】:
-
读/写操作通常是任何多线程解决方案的瓶颈,但在您的代码中,它似乎是唯一的操作。在这种情况下,多线程如果不能缩小它,就会将代码变成一个单一的瓶颈。
-
当你用20个文件试一试并检查修改后的文件是否正确?换句话说,即使 slow,您的解决方案是否会产生正确的输出?
-
你试过用
concurrent.futures.ThreadPoolExecutor吗?? -
如何确定问题出在 io 操作中?刚刚检查了几个输出,它们看起来是正确的,我没有尝试过 ThreadPoolExecutor
标签: python io threadpool python-multithreading