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.
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.
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.