python並發編程:多線程-開啟線程的兩種方式

來源:互聯網
上載者:User

標籤:用戶端   roc   cep   nbsp   習題   close   strong   nec   reading   

一 threading模組介紹

multiprocess模組完全模仿了threading模組的介面,二者在使用層面,有很大的相似性

二 開啟線程的兩種方式

方式一

from threading import Threadimport timedef sayhi(name):    time.sleep(2)    print("%s say hello" % name)if __name__ == ‘__main__‘:    t = Thread(target=sayhi, args=(‘mike‘, ))    t.start()    print("主線程")

  方式二

from threading import Threadimport timeclass Sayhi(Thread):    def __init__(self, name):        super().__init__()        self.name = name    def run(self):        time.sleep(2)        print(‘%s say hello‘ % self.name)if __name__ == ‘__main__‘:    t = Sayhi(‘mike‘)    t.start()    print("主線程")

  

三 練習題

1、基於多線程實現並發的通訊端通訊

用戶端:

from socket import *ip = ‘127.0.0.1‘port = 8081c = socket(AF_INET, SOCK_STREAM)c.connect((ip, port))while True:    msg = input("請輸入用戶端的資訊").strip()    if not msg:        continue    c.send(msg.encode(‘utf-8‘))    data = c.recv(1024)    print("收到的資訊:", data.decode(‘utf-8‘))

  

服務端:

from socket import *from threading import Threaddef talk(conn):    while True:        try:            data = conn.recv(1204)            if not data:                break            conn.send(data.upper())        except ConnectionResetError:            break    conn.close()def server(ip, port):    server_socket = socket(AF_INET, SOCK_STREAM)    server_socket.bind((ip, port))    server_socket.listen(1)    while True:        conn, addr = server_socket.accept()        p = Thread(target=talk, args=(conn,))        p.start()    conn.close()if __name__ == ‘__main__‘:    server(‘127.0.0.1‘, 8081)

 

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.