python3 进行与进程之间数据是隔离的

进程与进程之间数据是隔离的

from multiprocessing import Process


def func(lst, name):
    lst.append(66)
    print(name, lst)


if __name__ == '__main__':
    lst = [1, 2]
    p1 = Process(target=func, args=(lst, "进程1"))
    p2 = Process(target=func, args=(lst, "进程2"))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print("主进程结束", lst)

执行结果:

进程1 [1, 2, 66]
进程2 [1, 2, 66]
主进程结束 [1, 2]

python3 进行与进程之间数据是隔离的_第1张图片

 

global来演示进程之间数据是隔离的

from multiprocessing import Process


def func(name):
    print(f"{name}开始")
    global n
    n = 0
    print(f"{name}结束,n={n}")


if __name__ == '__main__':
    n = 100
    p1 = Process(target=func, args=("进程1",))
    p2 = Process(target=func, args=("进程2",))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print(f"主进程结束,n={n}")

执行结果:

进程1开始
进程1结束,n=0
进程2开始
进程2结束,n=0
主进程结束,n=100

python3 进行与进程之间数据是隔离的_第2张图片 

 

再看个会报错的程序

from multiprocessing import Process


def func(name):
    print(f"{name}开始")
    global n
    print(f"n={n}")
    n = 0
    print(f"{name}结束,n={n}")


if __name__ == '__main__':
    n = 100
    p1 = Process(target=func, args=("进程1",))
    p2 = Process(target=func, args=("进程2",))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print(f"主进程结束,n={n}")

执行结果:

进程1开始
Process Process-1:
Traceback (most recent call last):
  File "G:\python3.6\lib\multiprocessing\process.py", line 258, in _bootstrap
    self.run()
  File "G:\python3.6\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "G:\python28\code\day08\整理笔记\已记录\进程与进程之间数据是隔离的\222.py", line 7, in func
    print(f"n={n}")
NameError: name 'n' is not defined
进程2开始
Process Process-2:
Traceback (most recent call last):
  File "G:\python3.6\lib\multiprocessing\process.py", line 258, in _bootstrap
    self.run()
  File "G:\python3.6\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "G:\python28\code\day08\整理笔记\已记录\进程与进程之间数据是隔离的\222.py", line 7, in func
    print(f"n={n}")
NameError: name 'n' is not defined
主进程结束,n=100

通过对比可以发现,即使使用了global引用全局变量n,子进程里也没有成功的引入进来。

你可能感兴趣的:(python3 进行与进程之间数据是隔离的)