python并发编程之多进程(一):进程开启方式&多进程

时间:2021-05-20 20:09:46

一,进程的开启方式

利用模块开启进程

 from multiprocessing import Process
import time,random
import os
def piao(name):
print(os.getppid(),os.getpid())
print('%s is piaoing' %name)
# time.sleep(random.randint(1,3))
print('%s is piao end' %name)
if __name__ == '__main__':
p1=Process(target=piao,kwargs={'name':'alex',})
p2=Process(target=piao,args=('wupeiqi',))
p3=Process(target=piao,kwargs={'name':'yuanhao',})
p1.start()
p2.start()
p3.start()
print('主进程',os.getpid())

利用类开启进程

 from multiprocessing import Process
import time,random
import os
class Piao(Process):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
print(os.getppid(),os.getpid())
print('%s is piaoing' %self.name)
# time.sleep(random.randint(1,3))
print('%s is piao end' %self.name)
if __name__ == '__main__':
p1=Piao('alex')
p2=Piao('wupeiqi')
p3=Piao('yuanhao') p1.start()
p2.start()
p3.start()
print('主进程',os.getpid(),os.getppid())

二,多进程

服务器端

 from socket import *
from multiprocessing import Process
s=socket(AF_INET,SOCK_STREAM)
s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #就是它,在bind前加
s.bind(('127.0.0.1',8088))
s.listen(5)
def talk(conn,addr):
while True: #通信循环
try:
data=conn.recv(1024)
if not data:break
conn.send(data.upper())
except Exception:
break
conn.close()
if __name__ == '__main__':
while True:#链接循环
conn,addr=s.accept()
p=Process(target=talk,args=(conn,addr))
p.start()
s.close()

客户端

 from socket import *
c=socket(AF_INET,SOCK_STREAM)
c.connect(('127.0.0.1',8088)) while True:
msg=input('>>: ').strip()
if not msg:continue
c.send(msg.encode('utf-8'))
data=c.recv(1024)
print(data.decode('utf-8'))
c.close()