python - Python线程和多处理
问题描述
这是我的代码:
from threading import Thread
from multiprocessing import Process
def foo(x, y):
x += 5
y.append(5)
if __name__ == '__main__':
x = 0
y = []
thread = Thread(target=foo, args=(x, y,))
thread.start()
thread.join()
print 'Value of x is: ' + str(x)
print 'Value of y is: ' + str(y)
当我运行此代码时,结果是:
Value of x is: 0
Value of y is: [5]
当我将线程更改为进程时,结果是:
Value of x is: 0
Value of y is: []
为什么 x 的 +5 不起作用而 y 的附加起作用?
而且,为什么当我使用 Process 时,+5 和 append 都不起作用?
解决方案
我建议您在问基本问题之前阅读教程,因为它会节省每个人的时间,包括您的时间。
简而言之,当你使用时Thread
,主线程和启动线程共享相同的内存空间,但x
in 函数foo
是另一个内部x
但x
外部不同。所以你只改变内部x
而不是x
外部。此外,实际上y
也是一个 internal y
,但是您正在更改它所指向的内容而不是其自身。y.append(5)
您可以通过更改来确认这一点,y = [0]
以查看外部y
更改。
而且,当您使用 时Process
,主线程和启动的进程拥有完全独立的内存空间。
推荐阅读
- android - 如何在本机反应中读取和捕获android数据库中的所有短信?
- azure-functions - 从公共 Azure 函数到 Azure PostgreSQL 的安全连接
- google-apps-script - 在满足“IF”条件后仅运行一次谷歌应用脚本,每月一次
- interface - Hyperledger Fabric:如何获取部署的链码中包含的所有函数的名称及其参数和返回类型
- java - Fetch.lazy 不适用于 spring boot jpa,一定是什么问题?
- php - 如何将字符串转换为日期数据类型
- python - Python:更优雅的断言函数输入类型的方法
- python - Django Rest - 创建和操作方法返回错误 403 禁止
- php - 如何在上传前检查文件的 upload_max_filesize 和 post_max_size?
- mysql - 限制 SELECT 中的序号