Multithreaded file read python

穿精又带淫゛_ 提交于 2019-12-10 12:27:55

问题


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.

Any explanations are welcome.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/39906375/multithreaded-file-read-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!