python開發進程:進程開啟方式&多進程

來源:互聯網
上載者:User

標籤:開發   sea   rgs   add   init   nbsp   target   sel   decode   

一,進程的開啟方式

利用模組開啟進程

 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:break12             conn.send(data.upper())13         except Exception:14             break15     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()

 

python開發進程:進程開啟方式&多進程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.