天天看點

多程序不能共享全局變量 | 手把手教你入門Python之一百零六

上一篇: 程序和線程的差別 | 手把手教你入門Python之一百零五 下一篇: 程序間通信 | 手把手教你入門Python之一百零七 本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程 《Python入門2020最新大課》 ,主講人姜偉。

多程序不能共享全局變量

import os, multiprocessing, threading

n = 100


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


def demo():
    global n
    n += 1
    print('demo===={}裡n的值是{}'.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]           

配套視訊