首页 > 解决方案 > 如何使用线程读取文件内容并存储在局部变量中?

问题描述

我需要在线程中读取文件并将文件中存在的数据存储在局部变量中(在脚本中存在于线程之外的变量)。我将此变量作为参数发送到线程。如果我没有读取文件,而只是访问变量,那么一切正常。但是如果我正在读取一个文件,那么变量(这里是字典)就会出现空。我不确定为什么会这样。请让我知道为什么会发生这种情况以及我能做些什么。谢谢。

(我在 Windows 10 上使用 python 3.9.6)

import threading
import time
import os

def thread_function(filename: str, line_dict: dict, lock:threading.Lock):
  lock.acquire(blocking=True, timeout=5.8)
  with open(filename, 'r') as f:
    for id,line in enumerate(f):
      line_dict['line{}'.format(id)] = line
  lock.release()
  print('[from thread] Keys in Dictionary: \n{}'.format(line_dict.keys()))

line_dict = {}
lock = threading.Lock()

if __name__ == '__main__':
  t = threading.Thread(target=thread_function, args=('./lines.txt', line_dict, lock))
  t.start()
  print('[from main] Keys in Dictionary: \n{}'.format(line_dict.keys()))
  t.join()

标签: pythonmultithreading

解决方案


推荐阅读