Python processes, threads
Diagram of Python process, thread, and co-routines
The differences between Python processes and threads
• One process produces multiple threads
• Threads are shared memory, processes are independent
• Threads that are mostly service to the process cannot be run alone
Python threads
Python Threading methods
The start thread is ready to wait for CPU scheduling
SetName setting a name for a thread
GetName Get thread Name
Setdaemon set to background thread or foreground thread (default)
If it is a background thread, during the main thread execution, the background thread is executing, and after the main thread executes, the background thread stops regardless of whether it succeeds or not.
If it is the foreground process, the main thread execution process, the foreground process is also executing, after the main thread execution, wait for the foreground process to complete, the program stops
The join executes each thread one by one and continues execution after execution, making multithreading meaningless
Run thread executes the Run method of the thread object automatically after the CPU dispatch
Pyhton multithreading and single-threaded comparison
Module: Threading
ImportThreadingImport Time################ #不使用多线程 #############If you do not use multi-threading, it takes two seconds to execute only the F1 function on both sidesdefF1 (ARG): Time.sleep (1)#stop for a second . Print(ARG) F1 (1) F1 (2)############# #使用多线程 #################if multi-threading is used, functions are executed concurrently, requiring one secondT1 = Threading. Thread (target=f1,args= (1,))#This is a thread .T1.start () T2= Threading. Thread (target=f1,args= (2,)) T2.start ()
Python thread lock
Module: Threading. Rlock
Role: Because of random scheduling between threads, when multiple threads simultaneously modify the same piece of data may appear dirty data, so the lock appears, the same time only allow one thread to perform the operation
ImportThreadingImportTimenum= 10deffunc (L):GlobalNUM L.acquire ()#locked, blocking 10 threads here, because 10 threads are created below, threads are executed at the same time, so there is a lock at the same time that only one thread can execute.NUM-=1Time.sleep (2) Print(NUM) l.release ()#UnlockLock =Threading. Rlock () forIinchRange (10): T= Threading. Thread (target=func,args=(lock,)) T.start ()
Python producer consumer Model
Concept Map:
Concept:
In the P3 version upgrade project, the information server to receive a large number of client requests, the original kind of serialization of processing, simply unable to handle client requests in a timely manner, resulting in a large number of information server requests piled up, resulting in packet loss is very serious. Then the producer consumer model, between business requests and business processes, A list-type buffer is established, the server receives a business request, throws it in, and then receives the next business request, while multiple business processing threads go to the buffer to fetch the business request processing. This greatly improves the speed of the servers
Code:ImportThreadingImport TimeImportRandomImportQueue#Queue ModuledefProducer (Name,que):#producers whileTrue:que.put ('steamed Bun')#It's the equivalent of putting buns in the warehouse. Print('%s: made a bun'%name)#print out made a bun outTime.sleep (Random.randrange (5))#chef makes a bun in 5 secondsdefConsumer (Name,que):#Consumer whileTrue:Try:#exception handling, if there is no steamed buns to eat just wait for the chef to make bunsque.get_nowait ()Print('%s: ate a bun'%name)exceptException:Print(U'no buns.') Time.sleep (Random.randrange (3))#consumer eats a bun in 3 secondsQ= Queue. Queue ()#QueueP1 = Threading. Thread (target=producer,args=['Chef 1', Q])#The goal is to producer this function, and args is the argumentP2 = Threading. Thread (target=producer,args=['Chef 2', Q]) P1.start () P2.start () C1= Threading. Thread (target=consumer,args=['Zhang San', Q]) C2= Threading. Thread (target=consumer,args=['John Doe', Q]) C1.start () C2.start () Result: Chef 1: Cook a bun Cook 2: Made a steamed bun Zhang San: ate a bun John Doe: ate a bun no steamed bun has not steamed buns The cook 1: Did a bun John Doe: ate a bun no steamed bun has no bun
Python Inter-thread communication
Module: threading.event
Role: Python provides the event object for inter-thread communication, which is a signal flag set by the thread, and if the signal flag is true, other threads wait until the signal ends
Process:
1: Set the signal
Using the event's set () method, you can set the signal flag inside the event object to True, and the event object provides the IsSet () method to determine the state of its internal signal flag. When the set () method of the event object is used, the IsSet () method returns the true
2: Clear Signal
Use the Clear () method of the event to clear the signal flag inside the event object, set it to false, and when the clear () method of the event is used, the IsSet () method returns false
3: Wait
The wait () method using the event will only execute quickly and complete the return if the internal signal is true. When the internal signal flag bit of the event object is false, the wait () method waits for the band to be true before returning
Code:ImportThreadingImport Timedefprodecer ():Print('Chef: Wait for someone to buy buns')#print this sentence firstEvent.wait ()#After you print the previous sentence, wait for the consumer thread to turn false to true.Event.clear ()#then clears the status Print('Chef: Someone's here to buy buns.')#If consumer turns false to true, print this sentence Print('Chef: I'm making buns for you.')#in printing this sentenceTime.sleep (5)#stop for 5 seconds . Print('Chef: Steamed bun come on, take it.')#When you print this sentence, turn false to true to tell the other threadEvent.set ()defconsumer ():Print('Zhang San: go and buy a bun to eat') Event.set ()#Turn false into true to tell producer threadTime.sleep (2) Print('Zhang San: wait for the bun to be ready') whileTrue:ifEvent.isset ():Print('Thanks') Break Else: Print('Zhang San: all right?') Time.sleep (1) Result: Cook: wait for someone to buy steamed bun Zhang San: to buy a steamed bun to eat the chef: someone to buy steamed buns Cook: I am making steamed buns for you Zhang San: wait for the bun to do a good job Zhang San: ok Zhang San: okay? Zhang San: All right Zhang San
Python process thread