全局变量在多个进程中不共享

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一份给子进程,子进程可以访问主进程的资源,但是没有修改的权限。

猜你喜欢

转载自www.cnblogs.com/wuygblog/p/10759008.html