多進程無法共用全域變數|Python入門百講之十六

相關標籤:1.ApsaraDB RDS for MySQL
2. JavaScript中的原型與繼承

多進程無法共用全域變數|Python入門百講之十六

多進程無法共用全域變數。同一主進程中的兩個子線程。線程可以共用同一進程的全域變數,不同進程各自儲存一份全域變數,不共用。
多個進程無法共用全域變數
import os , multiprocessing, threading

n = 100


def test () :
global n
n += 1
print( 在test中n的值 'test===={} is {}' .format( os.getpid (), hex(id(n))))


def demo () :
global n
n += 1
print( 在demo中n的值 'demo===={} is {}' .format( os.getpid (), hex(id(n))))


print( threading.current_thread ().name)
test() # 101
demo() # 102

# 同一主進程中的兩個子線程。線程可以共用同一進程的全域變數

# t1 = threading.Thread (target=test)
# t2 = threading.Thread (target=demo)
# t1.start()
# t2.start()

# if __name__ == '__main__':
# 每個進程各自儲存一份全域變數,不共用全域變數
# p1 = multiprocessing.Process (target=test)
# p2 = multiprocessing.Process (target=demo)
# p1.start() # 101
# p2.start() # 101
樣本:
from multiprocessing import Process
import os

nums = [ 11 , 22 ]

def work1 () :
"""子進程要執行的代碼"""
print( "in process1 pid =%d , nums =%s" %( os.getpid (), nums ))
for i in range( 3 ):
nums.append ( i )
print( "in process1 pid =%d , nums =%s" %( os.getpid (), nums ))

def work2 () :
"""子進程要執行的代碼"""
nums.pop ()
print( "in process2 pid =%d , nums =%s" %( os.getpid (), nums ))

if __name__ == '__main__':
p1 = Process(target=work1)
p1.start()
p1.join()

p2 = Process(target=work2)
p2.start()

print('in process0 pid={} ,nums={}'.format(os.getpid(),nums))
運行結果:
in process1 pid=2707 ,nums=[11, 22]
in process1 pid=2707 ,nums=[11, 22, 0]
in process1 pid=2707 ,nums=[11, 22, 0, 1]
in process1 pid=2707 ,nums=[11, 22, 0, 1, 2]
in process0 pid=2706 ,nums=[11, 22]
in process2 pid=2708 ,nums=[11]

相關文章

探索更多特惠

  1. 簡訊服務與郵件服務

    50,000封郵件資源套件起步價低至1.99美元,120條簡訊起步價僅1.00美元

phone 聯絡我們
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.