One, Python concurrent programming Multi-Threading 1.1 threading Module
How to use from threading import Thread
#!/usr/bin/python#-*-coding:utf-8-*-from Threading Import threadfrom multiprocessing import processdef work (name ): print ('%s say hello '%name) if __name__ = = ' __main__ ': t=thread (' Egon ',) # target=work,args= (target=work,args= (' Egon ',)) T.start () print (' main thread ')
1.2 Two ways to open threads (same process)
#方式一from Threading Import Threadimport timedef Sayhi (name): time.sleep (2) print ('%s say hello '%name) if __name_ _ = = ' __main__ ': t=thread (target=sayhi,args= (' Egon ')) T.start () print (' main thread ') #方式二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 (' Egon ') T.start () print (' main thread ')
1.3 Multi-process and multi-threaded differences
#!/usr/bin/python#-*-coding:utf-8-*-from Threading Import threadfrom multiprocessing import processimport osdef work () : print (' hello ') if __name__ = = ' __main__ ': #在主进程下开启线程 t=thread (target=work) T.start () Print (' main thread/main process ')
Multithreaded concurrent sockets
#!/usr/bin/python#-*-coding:utf-8-*-from socket Import *from Threading Import Threaddef Server (ip,port): S.bind (( Ip,port)) S.listen (5) while True: conn, addr = s.accept () print (' client ', addr) t = Thread (target =talk, args= (conn, addr)) T.start () def talk (CONN,ADDR): #通信 try: While True: res=conn.recv (1024) if not res:break print (' Client%s:%s msg:%s '% (addr[0],addr[1],res)) Conn.send (Res.upper ()) Except Exception: pass finally: conn.close () if __name__ = = ' __main__ ': server (' 127.0.0.1 ', 8080 )
Client
#_ *_coding:utf-8_*_#!/usr/bin/env pythonimport sockets=socket.socket (socket.af_inet,socket. Sock_stream) S.connect ((' 127.0.0.1 ', 8080)) while True: msg=input (' >>: '). Strip () if not msg:continue s.send (Msg.encode (' Utf-8 ')) data=s.recv (1024x768) print (data)
Multi-threaded text Save input content
#!/usr/bin/python#-*-coding:utf-8-*-from Threading import Threadmsg_l=[]format_l=[]def Talk (): While True: Msg=input (' >>: '). Strip () if not msg:continue msg_l.append (MSG) def format (): While True: If msg_l: res=msg_l.pop () res=res.upper () Format_l.append (RES) def save (): While True: if format _l: res=format_l.pop () with open (' Db.txt ', ' a ', encoding= ' utf-8 ') as F: f.write ('%s\n '%res) if __name_ _ = = ' __main__ ': t1=thread (Target=talk) t2=thread (Target=format) t3=thread (target=save) T1.start () T2.start () T3.start ()
1.4 Threading Methods
Methods for thread instance objects
# isAlive (): Returns whether the thread is active. # getName (): Returns the thread name. # SetName (): Sets the thread name. Some of the methods provided by the threading module are: # threading.currentthread (): Returns the current thread variable. # threading.enumerate (): Returns a list that contains the running thread. Running refers to threads that do not include pre-and post-termination threads until after the thread has started and ends. # Threading.activecount (): Returns the number of running threads with the same result as Len (Threading.enumerate ()).
#!/usr/bin/python#-*-coding:utf-8-*-n=11111111111111111111111111111111111import timefrom Threading Import Threadimport threadingdef work (): time.sleep (2) print ('%s say hello '% (Threading.current_thread (). GetName () ) If __name__ = = ' __main__ ': t=thread (target=work) # T.setdaemon (True) #设置守护线程随主线程关闭 t.start () T.join () print (Threading.enumerate ()) #当前活跃的线程对象, is a list form print (Threading.active_count ()) #当前活跃的线程数目 print (' main thread ', Threading.current_thread (). GetName ())
Python Basics: Day10