是否需要使用Threads()中的args将共享变量显式传递给Python中的线程函数或直接访问它?

问题描述 投票:0回答:1

是否有必要显式地将共享变量传递给到线程函数,就像我在Python 3.10+中所示的(第一个示例)

操作系统是Windows 10,Python解释器是CPython

是否可以从函数中直接访问共享变量,如第二个代码示例所示。

# First example
# passing Arguments to the threading function using args 

import time
import threading


def update_list_A(var_list):
         var_list.append('A')

shared_list =[]

t1 = threading.Thread(target = update_list_A, args = (shared_list,)) #usings args to send shared variable

t1.start()
t1.join()

print(shared_list)

+----------------------------------------+

#second example
#directly accessing the shared variable from the threading function 

import time
import threading


def update_list_A():
         shared_list.append('A')

shared_list =[] #shared List 

t1 = threading.Thread(target = update_list_A, )

t1.start()
t1.join()

print(shared_list)

访问共享变量的正确方法是什么,是通过args还是直接访问?

python-3.x multithreading python-multithreading cpython
1个回答
0
投票

我想说这取决于上下文:

  • 对于共享变量很少的短代码,并且它们在一个小部分中声明和使用,您应该直接访问它。这使得代码更简单。

  • 对于较长的代码或复杂的流程,通过线程参数传递共享变量允许您形式化线程将访问的值。这有助于确保您不会访问您不想要的值,使测试更容易,并推动您最大限度地减少共享变量的数量。

© www.soinside.com 2019 - 2024. All rights reserved.