简体   繁体   English

Python线程和多处理

[英]Python threading and multiprocessing

This is my code: 这是我的代码:

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)

When i run this code, the result is: 当我运行此代码时,结果是:

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

When i change the Thread into Process, the result is: 当我将线程更改为进程时,结果是:

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

Why the +5 for x doesn't work while the append for y works? 为什么x的+5无效,而y的附加有效?

And, why when i use Process both +5 and append don't work? 而且,为什么当我同时使用Process +5和Append都不起作用?

I suggest you to read tutorial before asking basic questions as it will save everyone's time including yours. 我建议您在问基本问题之前先阅读教程 ,因为这将节省所有人的时间,包括您在内。

In short, when you use Thread , the main thread and launched thread share the same memory space but the x in function foo is another internal x but not the same x outside. 简而言之,当您使用Thread ,主线程和启动的线程共享相同的内存空间,但是函数foox是另一个内部x但外部不是相同的x So you just change the internal x but not the x outside. 所以,你只需要改变内部的x而不是x之外。 Further, actually y is also an internal y , but you are changing what it points to but not itself. 此外,实际上y也是内部y ,但是您要更改它指向的内容,但不能更改其本身。 You can confirm this by change y.append(5) to y = [0] to see will the outside y change. 您可以通过将y.append(5)更改为y = [0]来确认这一点,以查看外部y更改。

And, when you use Process , the main thread and launched process hold totally separate memory space. 并且,当您使用Process ,主线程和启动的进程将完全占用单独的内存空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM