在全局变量中存储程序配置数据有危险吗?

2024-04-25 23:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python程序,它被设计成systemd守护进程,当程序接收到SIGHUP信号时,它会重新读取配置文件。这些配置文件的解析内容保存在全局列表中。整个程序结构如下所示:

def read_confs(signalNumber, frame):
# Set the conf_files variable, print messages about
# received signal, etc and finally call the create_threads()

  create_threads(conf_files)


def create_threads(conf_files):

  global threads
  threads = []

  # Read the conf files and build the "threads" array.

  return threads


def main():

  global threads
  threads = create_threads(conf_files)

  while True:

    # Process the "threads" list, call other functions, and endlessly create
    # sub-processes based on "threads" list.


if __name__ == "__main__":

  signal.signal(signal.SIGHUP, read_confs)
  main()

如上所述,我使用的是全局列表类型变量threads,该变量在程序启动后以及每次程序收到SIGHUP时填充。它似乎工作得很好,但正如我所读到的,使用全局变量可能是危险的。像这样使用全局变量好吗?有没有更优雅/稳健的方法来达到同样的效果


Tags: andthe程序列表readsignalmainconf