···创建进程的两种方式
····第一种
from multiprocessing import Process
import time
def task(n):
print('我是子进程')
time.sleep(n)
print('子进程结束')
if __name__ == '__main__':
# args=(), kwargs={}
# t=Process(task,args=(1,))
t = Process(target=task, kwargs={'n': 1})
t.start() # 通知操作系统,开启进程,执行task函数
print('主')
····第二种:
from multiprocessing import Process
import time
class Task(Process):
def __init__(self, n):
super().__init__()
self.n = n
def run(self):
print('我是子进程')
time.sleep(self.n)
print('子进程结束')
if __name__ == '__main__':
t = Task(1)
# t.run(1) # 不是调用t.run(),而是调用t.start()
t.start()
print('主')
···join的使用
from multiprocessing import Process
import time
def task(n):
print('我是子进程')
time.sleep(n)
print('子进程结束')
if __name__ == '__main__':
ctime = time.time()
t = Process(target=task, kwargs={'n': 1})
t2 = Process(target=task, kwargs={'n': 2})
t.start()
t2.start()
t.join() # 等待t子进程执行完成
t2.join() # 等待t2子进程执行完成
print('主')
ctime2 = time.time()
print(ctime2 - ctime)
···进程之间数据隔离
from multiprocessing import Process
import time
age = 18
def task(n):
global age # 局部修改全局
age =