Multithreading
Co-process
IO model
Multithreading
#the PID of the thread is consistent with the main process PID fromThreadingImportThread fromMultiprocessingImportProcessImportOSdeftask ():Print('%s is running'%os.getpid ())if __name__=='__main__': T1=thread (target=task,) T2=thread (target=task,)#t1=process (Target=task,) #t2=process (Target=task,)T1.start () T2.start ( )Print('Master', Os.getpid ())
#Multithreading shares an in-process resource fromThreadingImportThread fromMultiprocessingImportPROCESSN=100defWork ():GlobalN N=0if __name__=='__main__': #p=process (target=work,) #P.start () #P.join () #print (' main ', N)T=thread (target=Work ,) T.start () T.join ( )Print('Master', N)
#two ways to turn on threads#how to turn on threads one: Use the thread provided by the replacement threading module fromThreadingImportThread fromMultiprocessingImportProcessdeftask ():Print('is running')if __name__=='__main__': T=thread (target=task,)#t=process (Target=task,)T.start ()Print('Master')#How to open a thread two: custom class, Inherit thread fromThreadingImportThread fromMultiprocessingImportProcessclassMyThread (Thread):def __init__(Self,name): Super ().__init__() Self.name=namedefRun (self):Print('%s is running'%self.name)if __name__=='__main__': T=mythread ('Egon') #t=process (Target=task,)T.start ()Print('Master')
#Multi-threaded exercises to share the same in-process address space#three tasks, one to receive user input, one to format the user input into uppercase, a formatted result into the file fromThreadingImportthreadmsg_l=[]format_l=[]defTalk (): whiletrue:msg=input ('>>:'). Strip () Msg_l.append (msg)defformat (): whileTrue:ifMsg_l:data=Msg_l.pop () format_l.append (Data.upper ())defSave (): whileTrue:ifFormat_l:data=Format_l.pop () with open ('Db.txt','a') as F:f.write ('%s\n'%data)if __name__=='__main__': T1=thread (target=Talk ) T2=thread (target=format) T3=thread (target=save) T1.start () T2.start () T3.start ()
#thread object Other related properties or methods fromThreadingImportThread,activecount,enumerate,current_threadImport Timedeftask ():Print('%s is running'%Current_thread (). GetName ()) Time.sleep (2)if __name__=='__main__': T=thread (target=task,) T.start () T.join ( )Print(T.is_alive ())Print(T.getname ())Print(Enumerate ())Print('Master') Print(Activecount ())
Co-process
IO model
PYTHON_DAY10 multi-line Cheng IO model