"Python core Programming" 18. Multithreaded Programming (III)

Source: Internet
Author: User

18.6 using the Threading module
#!/usr/bin/env python#-*-coding:utf-8-*-"""derive a child from the thread class and create an instance of the subclass"""ImportThreading fromTimeImportSleep, Ctimeloops= (4, 2)classMyThread (Threading. Thread):"""1. Subclass Thread Class 2. To call the constructor of the base class first, explicitly overwrite 3. Redefine the run () function"""    def __init__(Self, func, args, name="'): Super (MyThread, self).__init__() Self.name=name Self.func=func Self.args=argsdefRun (self): Self.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= MyThread (Loop, (I, loops[i]), loop.__name__)#to create an instance of a subclassthreads.append (t) forIinchNloops:threads[i].start () forIinchNloops:threads[i].join ()Print 'All do at :', CTime ()if __name__=='__main__': Main ()
18.7MyThread sub-class
#!/usr/bin/env python#-*-coding:utf-8-*-"""1. Separate subclasses to make the subclasses of thread more generic. 2. Add the GetResult () function to return the running result of the function. """ImportThreading fromTimeImportCTimeclassMyThread (Threading. Thread):def __init__(Self, func, args, name="'): Threading. Thread.__init__(self) self.name=name Self.func=func Self.args=argsdefGetResult (self):returnSelf.resdefRun (self):Print 'starting', Self.name,'At :', CTime () self.res=Apply (Self.func, Self.args)PrintSelf.name,'finished at:', CTime ()

18.8 Fibonacci, factorial, summation and

#!/usr/bin/env python#-*-coding:utf-8-*- fromMyThreadImportMyThread fromTimeImportCTime, Sleepdeffib (x):"""To find the sum of Fibonacci sequences"""Sleep (0.005)    ifX < 2:        return1returnFIB (x-2) + fib (x-1)defFAC (x):"""find factorial"""Sleep (0.1)    ifX < 2:        return1returnX * FAC (x-1)defsum_ (x):"""natural number accumulation and"""Sleep (0.1)    ifX < 2:        return1returnx + sum_ (x-1) Funcs= [FIB, FAC, SUM_]#put three functions in a listn = 12defMain (): Nfuncs= Range (len (funcs))#Nfuncs = Range (3)    Print '* * Single THREAD'  #single-threaded calculation of three functions     forIinchNfuncs:Print 'Staring', Funcs[i].__name__,'CTX', CTime ()#Print out function name, start run time        PrintFuncs[i] (N)#Print Calculation Results        PrintFuncs[i].__name__,'finished at:', CTime ()#Print out function name, end run time    Print '\n*** multiple THREADS'  #Multi-threaded computation of three functionsThreads = []     forIinchNfuncs:t= MyThread (Funcs[i], (n,), Funcs[i].__name__)#instantiation of three Mythread objectsThreads.append (t)#place three objects in a list     forIinchNfuncs:threads[i].start ()#Start Three Threads     forIinchNfuncs:threads[i].join ()#join () waits for the thread to end or time out, which allows the main thread to wait for threads to end        PrintThreads[i].getresult ()#the GetResult () method of the calling object    Print ' All done'if __name__=='__main__':#runs the script independently, that is, the main () function is called when this script is run directlyMain ()
18.9 Producer-Consumer issues
#!/usr/bin/env python#-*-Coding:utf8-*- fromRandomImportRandint#Randint randomly for production and consumption fromTimeImportSleep fromQueueImportQueue fromMyThreadImportMyThreaddefWriteq (queue):Print 'producing object for Q ...', Queue.put ('XXX', 1)#Put the xxx object into the queue and wait for space in the queue    Print "size Now", Queue.qsize ()#return Queue SizedefREADQ (Queue): Val= Queue.get (1)#fetching an object from the queue (consumption)    Print 'consumed Object form Q ... size now', Queue.qsize ()#return Queue Sizedefwriter (queue, loops):"""put an object in the queue one at a time, wait for a while, and then do the same thing for a given number of times"""     forIinchRange (Loops): Writeq (queue)#call Writeq, put in an objectSleep (Randint (1, 3))#random sleep 1-3 secondsdefReader (queue, loops):"""Take an object out of the queue one at a time, wait a while, and do the same thing for a given number of times"""     forIinchRange (Loops): READQ (queue) sleep (Randint (2, 5))#sleep longer than write, so that reader can get data when fetching dataFuncs=[Writer, Reader]nfuncs=Range (len (funcs))defMain (): Nloops= Randint (2, 5) Q= Queue (32)#create an object of size 32, and a Q bindingThreads= []     forIinchNfuncs:t= MyThread (Funcs[i], (Q, Nloops), Funcs[i].__name__)#Instantiate writer, reader these two objectsThreads.append (t)#put in an empty list     forIinchNfuncs:threads[i].start ()#Start Thread     forIinchNfuncs:threads[i].join ()#join () waits for the thread to end or time out, which allows the main thread to wait for threads to end    Print ' All done'if __name__=='__main__':#Run scripts independentlyMain ()

Python core programming 18. Multithreaded Programming (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.