18.1 No threading support
#!/usr/bin/env python#-*-coding:utf-8-*- fromTimeImportSleep, CTimedefloop0 ():Print 'start loop 0 at:', CTime () sleep (4) Print 'Loop 0 done at', CTime ()defLoop1 ():Print 'start loop 1 at:', CTime () sleep (2) Print 'Loop 1 done at:', CTime ()defMain ():"""sequential execution of two loops, that is, the first loop is completed before executing the second""" Print 'Staring at:', CTime () loop0 () Loop1 ( )Print 'All do at :', CTime ()if __name__=='__main__': Main ()
18.2thread Threading Support
#!/usr/bin/env python#-*-coding:utf-8-*-ImportThread fromTimeImportSleep,ctimedefloop0 ():Print 'start loop 0 at:', CTime () sleep (4) Print 'Loop 0 done at:', CTime ()defLoop1 ():Print 'start loop 1 at:', CTime () sleep (2) Print 'Loop 1 done at:', CTime ()defMain ():Print 'starting at:', CTime () Thread.start_new_thread (Loop0, ())#The function Start_new_thread () produces a new thread to run the function loop0 ()Thread.start_new_thread (LOOP1, ())#Ibid., two lines Chengtong simultaneous operationSleep (6)#main thread sleep wait; if the main thread (the program itself) does not stop, it will run the next statement directly without waiting for two threads to finish running Print 'All do at :', CTime ()if __name__=='__main__': Main ()
18.3 Using Threads and locks
#!/usr/bin/env python#-*-coding:utf-8-*-ImportThread fromTimeImportSleep, Ctimeloops= [4, 2]#1 Store The sleep time of each cycle#2 indirectly describes the number of loopsdefLoop (Nloop, Nsec, lock):"""record the number of loops and the time of sleep, and add locks""" Print 'Start Loop', Nloop,'At :', CTime () sleep (nsec)Print 'Loop', Nloop,'Done at :', CTime () lock.release ()#when the sleep () time ends, the release lock is used to notify the main thread that this child thread has endeddefMain ():"""contains three loops: Creates a lock, creates a thread and assigns a lock, ends the thread and unlocks""" Print 'starting at:', CTime () locks=[] Nloops= Range (len (loops))#Use the number of list elements to describe the number of loops forIinchNloops:lock= Thread.allocate_lock ()#Allocate_lock () function assign lock objectLock.acquire ()#Get Lock ObjectLocks.append (Lock)#Create a lock list forIinchNloops:thread.start_new_thread (Loop, (I, loops[i], locks[i]))#creating a looping thread forIinchNloops: whileLocks[i].locked ():#The main thread checks the lock object (the main thread is paused). The main thread executes the next statement when the thread ends and unlocks Pass Print 'All do at :', CTime ()if __name__=='__main__': Main ()
18.4 using the Threaging module
#!usr/bin/env python#-*-coding:utf-8-*-"""create an instance of thread (the class in the threading module) and pass it a function"""ImportThreading fromTimeImportSleep, Ctimeloops= [4, 2]#1 Store The sleep time of each cycle#2 indirectly describes the number of loopsdefLoop (Nloop, nsec):"""1 record loop number 2 record sleep time""" Print 'Start Loop', Nloop,'At :', CTime () sleep (nsec)Print 'Loop', Nloop,'Done at :', CTime ()defMain ():Print 'starting at:', CTime () Threads=[] Nloops= Range (len (loops))#Record cycle times forIinchNloops:t= Threading. Thread (Target=loop, args=(i, loops[i]))#1 Instantiate the thread class object, passing in the function (target) and the parameter (args) to get the thread instance returned: Thread Object T. #2 when instantiating (invoking) the thread class, the thread does not start immediately, like Thread.star_new_thread, so that it can be better synchronized. Threads.append (t)#Create a list of objects forIinchNloops:threads[i].start ()#start the execution of a thread forIinchNloops:threads[i].join ()#1 after calling the join () method, the main line routines wait until the thread ends to execute the next statement, which is clearer than the wireless loop (Spin lock) released with the wait lock. #2 If the main thread has other things to do besides waiting for the thread to finish (such as processing or waiting for other client requests), you do not have to call join (). Main Thread #will still wait for the thread to finish executing. Print 'All do at :', CTime ()if __name__=='__main__': Main ()
18.5 using the Threading module
#!/usr/bin/env python#-*-coding:utf-8-*-"""Create a thread instance and pass it to a callable class object"""ImportThreading fromTimeImportSleep, Ctimeloops= [4, 2]#1 storing cycle times for each list#2 Indirect description of the number of loopsclassThreadFunc (object):"""This class is intended to be as versatile as possible in calling functions, and is not limited to the loop () function. This class holds the function itself, the parameters of the function, and the string of the function's name. The constructor __init__ () does the assignment of these values. """ def __init__(Self, func, args, name="'): Super (ThreadFunc, self).__init__() Self.name=name Self.func=func Self.args=argsdef __call__(self):#used to execute functions in a classSelf.func (*Self.args)defLoop (Nloop, nsec):Print 'Start Loop', Nloop,'At :', CTime () sleep (nsec)Print 'Loop', Nloop,'Done at :', CTime ()defMain ():Print 'starting at:', CTime () Threads=[] Nloops=Range (len (loops)) forIinchNloops:t= Threading. Thread (Target=threadfunc (Loop, (I, loops[i]), loop.__name__)) #1. When instantiating a thread object, the Threadfunction object is also instantiated, i.e. two objects are instantiated #2. Since there are already parameters to be used, there is no need to add additional parameters to the constructor of the thread () #3. Here when the class object is transferred, and 18.4 is the functionthreads.append (t) forIinchNloops:threads[i].start () forIinchNloops:threads[i].join ()Print 'All do at :', CTime ()if __name__=='__main__': Main ()
"Python core Programming" 18. Multithreaded Programming (II)