Python线程中的全局变量与参数
我正在尝试更新一个字典,并使用多个线程读取一个列表,所以哪一个更好,最好是将列表和字典作为线程中的参数传递,还是使用全局关键字在线程中使用它们 即 vsPython线程中的全局变量与参数,python,multithreading,Python,Multithreading,我正在尝试更新一个字典,并使用多个线程读取一个列表,所以哪一个更好,最好是将列表和字典作为线程中的参数传递,还是使用全局关键字在线程中使用它们 即 vs 不仅仅是线程,而是通过使用参数您的函数将适用于参数数据的任何组合,而不仅仅是某些特定的全局变量 让我们假设你有: def foo(lst, lst_semaphore, dct, dct_semaphore): do_some_nice_stuff() 您可以用任何列表或命令垃圾邮件发送任何线程: threading.Thread(t
不仅仅是线程,而是通过使用
参数
您的函数将适用于参数数据的任何组合,而不仅仅是某些特定的全局
变量
让我们假设你有:
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)
因此,使用参数将使您的代码更易于重用。不仅仅是线程问题,而是通过使用
参数,您的函数将适用于参数数据的任何组合,而不仅仅是某些特定的全局变量
让我们假设你有:
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)
因此,使用参数将使代码更易于重用