First, the threading module introduces the Multiprocess module completely imitate the interface of the threading module, both in the use level, there is a great similarity, so no longer detailed introduction two ways to open the thread one: from threading import Thread Import Time Import random def task (name): Print ('%s is running '%name) time.sleep (Random.randint (1,3)) print ('%s ') End '%name #注意: The process () in Windows must be placed in # if __name__ = = ' __main__ ': under if __name__ = = ' __main__ ': T1=thread (Target=task,args = (' ALex ',)) T1.start () print (' main function ') #linux下的就不需要if __name__ = = ' __main__ ': T1=thread (target=task,args= (' renwu1 ',)) T1.start () print (' main function ') mode two: from threading import Thread Import time Import random class task (Thread): Def __init__ (self,n AME): Super (). __init__ () Self.name=name def run (self): print ('%s is runnging '%self.name) time.sleep (Random.randint (1,3 ) Print ('%s is end '%self.name) t1=task (' renwu1 ') t1.start (' main function ') three, the difference between opening multiple threads in a process and opening multiple sub-processes under a process 1, compare who's open fast From threading import Thread from multiprocessing import Process def task (): print (' Hello ') t1=thread (target=task) T1.star T () print (' main function/thread ') p1=process (target=task) p1.stArt () print (' main function/process ') 2, view PID from threading import Thread from multiprocessing import Process import os def task (): Print ( ' Hello ', Os.getpid () # Open multiple threads under the main process, each thread is the same as the PID of the main process T1=thread (target=task) t2=thread (target=task) T1.start () T2.start ( Print (' main function Pid/thread ', Os.getpid ()) # Open multiple processes under the main process, each with a different PID p1=process (target=task) p2=process (target=task) P1.start ( ) P2.start () print (' main function Pid/process ', Os.getpid ()) 3, thread sharing within the same process process data from the threading import thread from multiprocessing import Process def task (): Global n n=0 n=1 p=process (target=task) P.start () P.join () print (' main function/process ', N) t=thread (target=task) T.S Tart () T.join ()
Multi-Threading programming for Python concurrent programming