import os
from multiprocessing import Process
import time
def func(args,args2):
print(args,args2)
time.sleep(1)
print('子进程:',os.getpid())
print('子进程的父进程:',os.getppid()) #查看当前进程的父进程号
print(12345)
if __name__ == '__main__':
p = Process(target=func,args=('参数1','参数2')) #注册 #p是一个进程对象 主进程
p.start() #启动一个子进程
print('*'*10)
print('父进程:',os.getpid()) #查看当前进程的进程号
print('父进程的父进程:',os.getppid()) #查看当前进程的父进程号
#进程的生命周期
# 主进程
# 子进程
# 开启了子进程的主进程:自己代码长,等待自己的代码执行结束
# 子进程的执行时间长,主进程会在主进程代码执行完毕之后等待子进程执行完毕之后,主进程才结束
from multiprocessing import Process import time def func(arg1,arg2): time.sleep(1) print('*'*arg2) if __name__ == '__main__': p_lst = [] for i in range(10): p = Process(target=func,args=(10*i,20*i)) p.start() p_lst.append(p) [p.join() for p in p_lst] print('运行完了')
多进程创建多个文件
from multiprocessing import Process import time,os def func(filename,content): with open(filename,'w') as f: f.write(content*10*'*') if __name__ == '__main__': p_lst = [] for i in range(5): p = Process(target=func,args=('info%s'%i,i)) p_lst.append(p) p.start() [p.join() for p in p_lst] print('运行完了') print([i for i in os.walk(r'D:PythonPY9pythonpy9-day36--多进程及进程锁')])
开启多进程的第二种方式
自定义类 继承Process类
必须实现一个run方法,run方法中是在子进程中执行的代码
import os from multiprocessing import Process class MyProcess(Process): def run(self): print(os.getpid()) if __name__ == '__main__': print('主:',os.getpid()) p1 = MyProcess() p1.start() p2 = MyProcess() p2.start()
多进程socket实现
#server import socket from multiprocessing import Process def serve(conn): ret = '你好'.encode('utf-8') conn.send(ret) msg = conn.recv(1024).decode('utf-8') print(msg) conn.close() if __name__ == '__main__': sk = socket.socket() sk.bind(('127.0.0.1',8080)) sk.listen() while True: conn,addr = sk.accept() p =Process(target=serve,args=(conn,)) p.start() sk.close() #client import socket sk = socket.socket() sk.connect(('127.0.0.1',8080)) msg = sk.recv(1024).decode('utf-8') print(msg) msg2 = input('>>>>').encode('utf-8') sk.send(msg2) sk.close()
守护进程
from multiprocessing import Process import time def func(): while True: time.sleep(0.1) print('我还活着') if __name__ == '__main__': p = Process(target=func) p.daemon = True #设置子进程为守护进程 p.start() i = 0 while i<5: print('我是一个socket server') time.sleep(1) i+=1 #守护进程会随着主进程的代码执行完毕而结束
锁
import json import time from multiprocessing import Process from multiprocessing import Lock def show(i): with open('ticket') as f: dic = json.load(f) print('余票:%s'%dic['ticket']) def buy_ticket(i,lock): lock.acquire() #拿钥匙进门 with open('ticket') as f: dic = json.load(f) time.sleep(0.1) if dic['ticket'] > 0: dic['ticket'] -= 1 print('