简体   繁体   English

迭代Python文件对象线程是否安全?

[英]Is iterating over a Python file object thread safe?

While searching for a neat solution to this problem I was wondering if iterating over a Python file object is thread safe or not. 在寻找这个问题的一个简洁的解决方案时,我想知道迭代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()

My question is, if the example above is safe, or if not, what is an easy way to get a thread-safe file object (for reading a file line by line, writing is not required). 我的问题是,如果上面的示例是安全的,或者如果没有,那么获取线程安全文件对象的简单方法是什么(用于逐行读取文件,不需要写入)。

No, file I/O is not thread safe. 不,文件I / O不是线程安全的。 Locking is a solution, but I think the option of having a single thread deal with each external resource works better. 锁定是一种解决方案,但我认为让单个线程处理每个外部资源的选项效果更好。 Other threads send work requests to the dedicated thread on a Queue.Queue instance (and provide another queue of their own in case they need result(s) back), the dedicated thread spends most of its time waiting on a .get on that queue and whenever it gets a request it deals with it, possibly returning the results. 其他线程将工作请求发送到Queue.Queue实例上的专用线程(并在需要返回结果的情况下提供自己的另一个队列),专用线程将大部分时间用于等待该队列上的.get每当它收到请求时,它就会处理它,可能会返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM