【发布时间】:2013-09-13 08:09:34
【问题描述】:
在寻找this problem 的简洁解决方案时,我想知道迭代 Python 文件对象是否是线程安全的。
from concurrent.futures import ThreadPoolExecutor
import sys, time
f = open("big_file")
def worker():
running = True
while running:
try:
line = next(f)
except StopIteration:
return
# process line
time.sleep(3)
sys.stdout.write(line + "\n")
no_workers = 4
with ThreadPoolExecutor(max_workers=no_workers) as e:
for _ in range(no_workers):
e.submit(worker)
f.close()
我的问题是,如果上面的示例是安全的,或者如果不是,那么获取线程安全文件对象的简单方法是什么(对于逐行读取文件,不需要写入)。
【问题讨论】:
-
相当安全的方法是一次读取它,然后遍历每一行。这符合您的需求吗?
-
@Tadeck 遗憾的是没有,因为文件太大而无法放入内存
标签: python multithreading