[英]Python threading and multiprocessing
這是我的代碼:
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
,主線程和啟動的線程共享相同的內存空間,但是函數foo
的x
是另一個內部x
但外部不是相同的x
。 所以,你只需要改變內部的x
而不是x
之外。 此外,實際上y
也是內部y
,但是您要更改它指向的內容,但不能更改其本身。 您可以通過將y.append(5)
更改為y = [0]
來確認這一點,以查看外部y
更改。
並且,當您使用Process
,主線程和啟動的進程將完全占用單獨的內存空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.