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

一,进程的开启方式

利用模块开启进程

 1 from multiprocessing import Process
 2 import time,random
 3 import os
 4 def piao(name):
 5     print(os.getppid(),os.getpid())
 6     print('%s is piaoing' %name)
 7     # time.sleep(random.randint(1,3))
 8     print('%s is piao end' %name)
 9 if __name__ == '__main__':
10     p1=Process(target=piao,kwargs={'name':'alex',})
11     p2=Process(target=piao,args=('wupeiqi',))
12     p3=Process(target=piao,kwargs={'name':'yuanhao',})
13     p1.start()
14     p2.start()
15     p3.start()
16     print('主进程',os.getpid())

 

利用类开启进程

 1 from multiprocessing import Process
 2 import time,random
 3 import os
 4 class Piao(Process):
 5     def __init__(self,name):
 6         super().__init__()
 7         self.name=name
 8     def run(self):
 9         print(os.getppid(),os.getpid())
10         print('%s is piaoing' %self.name)
11         # time.sleep(random.randint(1,3))
12         print('%s is piao end' %self.name)
13 if __name__ == '__main__':
14     p1=Piao('alex')
15     p2=Piao('wupeiqi')
16     p3=Piao('yuanhao')
17 
18     p1.start()
19     p2.start()
20     p3.start()
21     print('主进程',os.getpid(),os.getppid())

 

二,多进程

服务器端

 1 from socket import *
 2 from multiprocessing import Process
 3 s=socket(AF_INET,SOCK_STREAM)
 4 s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) #就是它,在bind前加
 5 s.bind(('127.0.0.1',8088))
 6 s.listen(5)
 7 def talk(conn,addr):
 8     while True: #通信循环
 9         try:
10             data=conn.recv(1024)
11             if not data:break
12             conn.send(data.upper())
13         except Exception:
14             break
15     conn.close()
16 if __name__ == '__main__':
17     while True:#链接循环
18         conn,addr=s.accept()
19         p=Process(target=talk,args=(conn,addr))
20         p.start()
21     s.close()

 客户端

 1 from socket import *
 2 c=socket(AF_INET,SOCK_STREAM)
 3 c.connect(('127.0.0.1',8088))
 4 
 5 while True:
 6     msg=input('>>: ').strip()
 7     if not msg:continue
 8     c.send(msg.encode('utf-8'))
 9     data=c.recv(1024)
10     print(data.decode('utf-8'))
11 c.close()

 

 
 
 
posted @ 2018-02-02 17:02  带带大师兄丶  阅读(1120)  评论(0编辑  收藏  举报
欢迎第 Free Counters个访客