1. Objective: In order to run independent sub-tasks in parallel, greatly improve the efficiency of the whole task (asynchronous task, compute-intensive Task) Userrequestthread: Responsible for reading the user's input, may be an I/O channel. The program may create multiple threads, one per user, and the request will be placed in the queue. Requestprocessor: A thread responsible for fetching and processing requests from the queue, providing output replythread for the following thread: it is responsible to take out the output to the user, if it is a network application, send the results, Otherwise it will be stored in the local file system or database. Each thread has its own clear task. 2. Line threads start, sequential execution and end three stages 3. Global interpreter Lock (GIL): Access to a Python virtual machine is controlled by a global control lock that ensures that only one thread is running at the same time, and the Python virtual machine runs as follows: (1), set GIL (2) Switch a thread to run (3) run: A. Specify the number of bytecode instructions or B. Thread to give control (4) Set thread to Hibernate (5) Unlock Gil (6) Repeat above 4. Using Threads in Python: _ The thread and threading modules and the queue module. where _thread) and threading modules allow users to create and manage threads themselves. The queue module allows the user to create a queued data structure that can be used for sharing between multiple threads note: To avoid using the _thread module. _thread.start_new_thread and Exit 5.threading Module 5.1Thread class: With the thread class, you can create threads in a variety of ways: a. Create an instance of thread and pass it to a function B. Creates an instance of thread, creating a class object called by a section of it. C. Derive a subclass from thread and create an experimental function of this subclass ; Start (), run (), join (): Thread hangs, GetName (), SetName () isAlive (), Isdaemon (), Setdeamon ()usage: Threading.Thread(Group=none,Target=none,Name=none,args= (),kwargs={},*,Daemon=none)When all the threads are created and then the start () function is called together, instead of creating a startup one. Instead of managing a bunch of locks, simply calling the join () function on each thread can be an example: 1. Building a threading class
#-*-encoding:utf-8-*-ImportThreading fromTimeImportCTimeclassMyThread (Threading. Thread):def __init__(self,func,args,name="'): Threading. Thread.__init__(self) self.func=func Self.args=args Self.name=namedefGetResult (self):returnSelf.resdefRun (self):Print('starting', Self.name,' at', CTime ()) Self.res=self.func (Self.args[0],self.args[1])## # #此处需要修改 Print(Self.name,'finished at:', CTime ())
1. Several recursive operations
fromMyThreadImportMyThread fromTimeImportCtime,sleepdeffib (x): Sleep (0.005) ifX<2: return1Else: return(Fib (x-2) +fib (x-1))defFAC (x): Sleep (0.1) ifX<2: return1return(X*fac (x-1))defsum (x): Sleep (0.1) ifX<2: return1return(X+sum (x-1)) Funcs=[Fib,fac,sum]n=12defMain (): Nfunc=Range (len (funcs))Print('*****single THREAD') forIinchNfunc:Print('starting', Funcs[i].__name__,'CTX', CTime ())Print(Funcs[i] (n))Print(Funcs[i].__name__,'finished at:', CTime ())Print('******multiple THREADS') Threads=[] forIinchNfunc:t=mythread (Funcs[i], (n,), Funcs[i].__name__) threads.append (t) forIinchNfunc:threads[i].start () forIinchNfunc:threads[i].join ()Print(Threads[i].getresult ())Print(' All done')if __name__=='__main__': Main ()
Solve producer and consumer problems with the queue module
fromRandomImportRandint fromTimeImportSleep fromQueueImportQueue fromMyThreadImportMyThreaddefWriteq (queue):Print('producing object for Q ...') Queue.put ('XXX', 1) Print('size Now', Queue.qsize ())defREADQ (Queue): Val=queue.get (1) Print('consumed object from Q...size now', Queue.qsize ())defWrite (queue,loops): forIinchRange (Loops): Writeq (queue) sleep (Randint (1,3))defReader (queue,loops): forIinchRange (Loops): READQ (queue) sleep (Randint (2,5)) Funcs=[Write,reader]nfunc=Range (len (funcs))defMain (): Nloops=randint (2,5) Q=queue (32) Threads=[] forIinchNfunc:t=mythread (Funcs[i], (Q,nloops), Funcs[i].__name__) threads.append (t) forIinchNfunc:threads[i].start () forIinchNfunc:threads[i].join ()Print(' All done')if __name__=='__main__': Main ()
Python multithreaded programming