首页 > 解决方案 > 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 都不起作用?

标签: pythonmultithreadingmultiprocessingpython-multiprocessingpython-multithreading

解决方案


我建议您在问基本问题之前阅读教程,因为它会节省每个人的时间,包括您的时间。

简而言之,当你使用时Thread,主线程和启动线程共享相同的内存空间,但xin 函数foo是另一个内部xx外部不同。所以你只改变内部x而不是x外部。此外,实际上y也是一个 internal y,但是您正在更改它所指向的内容而不是其自身。y.append(5)您可以通过更改来确认这一点,y = [0]以查看外部y更改。

而且,当您使用 时Process,主线程和启动的进程拥有完全独立的内存空间。


推荐阅读