多线程文件读取python [英] Multithreaded file read python

查看:582
本文介绍了多线程文件读取python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import threading


def read_file():
  f = open('text.txt')
  for line in f:
      print line.strip() ,' : ',  threading.current_thread().getName()

if __name__ == '__main__':
  threads = []
  for i in range(15):
    t = threading.Thread(target=read_file)
    threads.append(t)
    t.start()

问题:每个线程会从上面的文件中只读取一次每行,还是给定线程最终可能会读取两次行?

Question: Will each thread read each line only once from the file above or there are chances that a given thread can end up reading a line twice?

我的理解是,较晚启动的线程将覆盖较早启动的线程的文件句柄,从而导致较早的线程最终读取两次或两次或更多次的行.

My understanding was that a thread started later will overwrite the file handle for the thread started earlier causing the earlier thread to end up reading few lines twice or thrice or more times.

运行此代码时,结果与预期的结果不同.

When I ran this code the outcome was different from what I expected to happen.

欢迎任何解释.

推荐答案

每个线程独立运行您的函数;该函数的每个副本都以本地文件的形式打开该文件,该文件不会共享.每个Python文件对象都完全独立地跟踪读取状态;每个都有自己的操作系统级文件句柄.

Each thread runs your function independently; each copy of the function opens the file as a local, which is not shared. Each Python file object tracks reading state completely independently; each has their own OS-level file handle here.

所以不,如果没有其他改变文件内容的情况,那么每个线程只会看到每行一次,就像单独的 processes 试图读取文件一样

So no, if nothing else is altering the file contents, each thread will see each line just once, just the same as if separate processes tried to read the file.

这篇关于多线程文件读取python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆