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

时间:2017-09-12 07:04:46

标签: python multithreading

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

mythread(list, list_semaphore, dict, dict_semaphore)

vs

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

1 个答案:

答案 0 :(得分:0)

不仅仅是线程的问题,但通过使用<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> ,您的函数将适用于任何组合的参数数据,而不仅仅是某些特定的{{} 1}}变量。

让我们说你有这个:

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

因此,使用参数将使您的代码更可重用。