This article mainly introduces the detailed explanation of the principle of Python timer thread pool. The article introduces the sample code in great detail. It has certain reference learning value for everyone's study or work. Friends who need it can refer to
The timer performs cyclic tasks:
Knowledge reserve
Timer(interval, function, args=None, kwargs=None)
interval ===》 Time interval unit is s
function ===》 Customized execution function
Timer class using threading
start() is the general method to start execution
cancel () is a method to cancel execution
Ordinary single timing execution
from threading import Timer
import time
# Ordinary one-shot timer
def handle():print("Normal one-shot timer function is executed");
t1=Timer(interval=1,function=handle);
t1.start();
Timed loop execution
from threading import Timer
import time
# Cycle timer
def loop_handle():print("Loop timer timer function is executed");
global t2;
t2=Timer(interval=1,function=loop_handle);
t2.start();
t2=Timer(interval=1,function=loop_handle);
t2.start();
time.sleep(5);#Stop the main thread for 5s;
t2.cancel(); #t2 blocks the main thread for 5s and t2 executes for 5s
Thread pool technology
basic concept
Several threads are created when the program starts and saved in memory. When the thread is started and executed, it will not be destroyed, but will wait for the next use.
i: It saves the time of creating process and destroying process, greatly reducing the cost of process
achieve
Preemptive: The execution order of threads in the thread pool is not fixed. This method is implemented using the submit () method of ThreadPoolExecutor.
The specific execution of the thread is random, and the executed function can also be inconsistent
The function executed by that thread crashes and does not affect the operation of other threads in the entire thread pool
Use with syntax to simplify operations
Non-preemptive: Threads will execute in the order in which they are called. This method uses the map () method of ThreadPoolExecutor to achieve
The functions processed by each thread are the same. A function executed by a thread crashes, and the whole process crashes
Basic code
from concurrent.futures import ThreadPoolExecutor #Import thread pool
import time
def printName(name):print("first name",name);
time.sleep(2);
nameList=['Tom','jirl','steam'];
# Preemptible thread pool
start2=time.time();withThreadPoolExecutor(3)as executor:for i in nameList:#Because the function executed each time is inconsistent, the parameters must be passed separately
executor.submit(printName,i);
end2=time.time();print("2 speed:",str(end2-start2));
# Non-preemptible thread pool
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts