繁体   English   中英

Python线程中的全局变量与参数

[英]Global variable vs Parameters in a Python thread

我正在尝试更新字典并使用多个线程读取列表,所以哪个更好,是将列表和字典作为线程中的参数传递还是通过global关键字在线程中使用它们更好。

即。

mythread(list, list_semaphore, dict, dict_semaphore)

mythread():
    global dict
    global dict_semaphore
    global list
    global list_semaphore

不仅仅是线程问题 ,而且通过使用parameters您的函数将可用于参数数据的任何组合 ,而不仅是某些特定的global变量。

可以说你有这个:

def foo(lst, lst_semaphore, dct, dct_semaphore):
    do_some_nice_stuff()

您可以使用任何列表或字典对任何线程进行垃圾邮件处理:

threading.Thread(target=foo, args = (lst1, lst_semaphore1, dct1, dct_semaphore1))
threading.Thread(target=foo, args = (lst2, lst_semaphore2, dct1, dct_semaphore1))
threading.Thread(target=foo, args = (lst2, lst_semaphore2, dct2, dct_semaphore2))

如果使用globals ,则必须为每个组合重新定义一个函数:

def foo():
    global lst1
    global lst_semaphore1
    global dct1
    global dct_semaphore1
    do_nice_stuff()
...
def foo2():
    global lst2
    global lst_semaphore2
    global dct2
    global dct_semaphore2
    do_nice_stuff()


threading.Thread(target=foo)
threading.Thread(target=foo1)
threading.Thread(target=foo2)

因此,使用参数将使您的代码在大多数情况下更易于重用。

暂无
暂无

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

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