開發與維運

多進程不能共享全局變量

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《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]

配套視頻

Leave a Reply

Your email address will not be published. Required fields are marked *