全局變量在多個進程中不共享


import time
from multiprocessing import Process

money = 100

def run1():
    global money #在進程中無法使用全局變量
    money = 200
    for i in range(3):
        # print("sunck is a good man")
        time.sleep(1)
    print("run1------money:", money)

def run2():
    money = 300
    for i in range(5):
        # print("kaige is a cool man")
        time.sleep(1)
    print("run2------money:", money)


if __name__ == "__main__":
    t1 = time.time()

    #在創建子進程時會將主進程的資源拷貝到子進程中,子進程單獨有一份主進程中的數據,相互不應響應
    pro1 = Process(target=run1, args=())
    pro2 = Process(target=run2, args=())
    pro1.start()
    pro2.start()

    pro1.join()
    pro2.join()

    print("main-----mony:", money)




    t2 = time.time()
    print("耗時:%2f"%(t2-t1))
run1------money: 200
run2------money: 300
main-----mony: 100
耗時:5.236128

 主進程文件里定義變量money,子進程run1,run2里可以訪問變量money,但是不可以修改,原理是創建子進程是會將主進程的資源copy一份給子進程,子進程可以訪問主進程的資源,但是沒有修改的權限。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM