简体   繁体   English

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

[英]Global variable vs Parameters in a Python thread

I am trying to update a dictionary and read a list using multiple threads so which one is better, is it better to pass the list and dictionary as parameters in the thread or use them in the thread using the global keyword. 我正在尝试更新字典并使用多个线程读取列表,所以哪个更好,是将列表和字典作为线程中的参数传递还是通过global关键字在线程中使用它们更好。

ie. 即。

mythread(list, list_semaphore, dict, dict_semaphore)

vs

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

Is not just a matter of threading , but by using parameters your function will work for any combination of parameters data, not just some specific global variables. 不仅仅是线程问题 ,而且通过使用parameters您的函数将可用于参数数据的任何组合 ,而不仅是某些特定的global变量。

Lets say you have this: 可以说你有这个:

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

You can spam any thread doind that with any list or dict: 您可以使用任何列表或字典对任何线程进行垃圾邮件处理:

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))

If you use globals you will have to redefine a function for each combination: 如果使用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)

So, using parameters will make your code more reusable mostly always. 因此,使用参数将使您的代码在大多数情况下更易于重用。

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

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