Python线程和多处理

时间:2018-05-23 06:12:51

标签: python multithreading multiprocessing python-multiprocessing python-multithreading

这是我的代码:

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]

当我将Thread更改为Process时,结果为:

Value of x is: 0
Value of y is: []

为什么x的+5在y的追加工作时不起作用?

而且,为什么当我使用Process + +并附加不工作?

1 个答案:

答案 0 :(得分:0)

我建议您在提出基本问题之前阅读tutorial,因为它可以节省每个人的时间,包括您的。

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

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