Introduction of a threading module
The Multiprocess module completely imitates the interface of the threading module, which has a great similarity in the use level.
Two ways to open a thread
Way One
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 ("Main thread")
Way Two
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 ("Main thread")
Three exercises
1, multi-threaded implementation of the concurrent socket communication
Client:
From socket import *ip = ' 127.0.0.1 ' port = 8081c = Socket (af_inet, Sock_stream) c.connect ((IP, port)) while True: msg = Input ("Please enter the client's information"). Strip () if not msg: continue c.send (Msg.encode (' Utf-8 ')) data = C.RECV (1024 print ("Message Received:", Data.decode (' Utf-8 '))
Service side:
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 concurrent Programming: multithreading-two ways to turn on threads