Is it necessary to pass a shared variable explicitly设置为如下所示的线程函数(第一个示例),如下面的代码所示

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

从第二个代码示例所示的函数是否可以设置为directly access the shared variable.

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

imp或t time
imp或t 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 

imp或t time
imp或t 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)

What is the c或rect way to access the shared variable, is it through args 或 directly?

推荐答案

我想说,这取决于背景:

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

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

这与global variables类似.

Python-3.x相关问答推荐

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

pandas查找另一列中是否存在ID

Python GUI:tkinter应用程序作为Windows的实时桌面

我无法直接在 VSCode 中运行该程序,但可以使用 VScode 中的终端运行它

Python根据条件从多行读取值

如何获取实例化 `types.GenericAlias` 的下标类?

从 LeetCode 的 Python 解决方案类中理解关键字 self

try 使用 GEKKO 求解非线性方程组.系统有多种解决方案,但 GEKKO 给出了错误的解决方案.我该如何解决?

隐藏Cartopy中高纬度非矩形投影的右侧轴(纬度)标签

以编程方式映射 uniprot ID 时如何解决 400 客户端错误?

使用正则表达式提取字符串之间的文本

为直方图中的每个 bin 绘制不同的 colored颜色 (Matplotlib)

为什么 List 不能包含多种类型?

如何从 Python 3.5 降级到 Python 3.4

使用逗号时,除了处理程序中的语法无效

IronPython 3 支持?

使用 Tensorflow 2.0 在 MNIST 上实现自定义神经网络?

导入父目录进行简要测试

TypeError:无法实例化类型元组;使用 tuple() 代替

在 PostgreSQL 上使用 SQLAlchemy 创建全文搜索索引