Python timer thread pool

Timer cyclic task:

 

  • Knowledge base
  1.   Timer(interval, function, args=None, kwargs=None)
  2. interval === "time interval in s
  3. function === "custom function performed
  • Use threading Timer class
  1. start () method is commonly started
  2. cancel () method to cancel execution of
  • Normal Single timing of execution
Threading from Import the Timer
 Import Time 
# ordinary single-shot timer 
DEF handle (): 
Print ( "normal shot timer function is executed" ); 
T1 = the Timer (interval The. 1 =, = function handle); 
t1.start ();

 

Performing a timing loop

Threading the Timer Import from 
Import Time 
# Cycle Timer 
DEF loop_handle (): 
Print ( "timer function is executed cycle timer"); 
Global T2; 
T2 = the Timer (interval The. 1 =, = loop_handle function); 
t2.start () ; 

T2 = the Timer (interval the. 1 =, = loop_handle function); 
t2.start (); 

the time.sleep (. 5); the main thread stops # 5S; 
t2.cancel (); # T2 in the primary main execution thread blocks 5s t2 5s

  

Thread pool

 

 

basic concepts

  • When the program starts on a number of threads created and saved to memory. When the thread is started and executed, it does not destroyed, but wait for the next re-use.

    i: saving time destroy the process of creating the process, greatly reduce the overhead of process

  • achieve
  1. Preemptive: thread pool thread execution order is not fixed. The manner of using ThreadPoolExecutor submit () method implementation.
    1.       Specific function to perform that thread is random, and may also be inconsistent execution
    2.   Run the function thread of execution appeared a crash, does not affect the whole other thread pool thread
    3.   Use with syntax streamline operations
  • Non-preemptive: thread will execute the order calls. This way of using ThreadPoolExecutor map () method to achieve
  1.   Each thread processing functions are the same, one thread executes a function of the collapse, the overall collapse

The basic code

concurrent.futures from Import the ThreadPoolExecutor introduced thread pool #
 Import Time 

DEF printName (name): 
Print ( "name" , name); 
the time.sleep ( 2 ); 
nameList = [ 'Tom', 'jirl', 'Steam' ]; 
# preemptive thread pool 
start2 = the time.time (); 
with the ThreadPoolExecutor ( . 3 ) aS Executor:
 for I in nameList: # inconsistent because each execution of the function, the parameters to be passed separately 
executor.submit (printName, I); 
end2 = the time.time (); 
Print ( "Speed 2:", STR (end2- start2)); 
# non-preemptive thread pool

 

 


The number of threads formula:
Formula

 

 

Experience
(1) initialize certain number of threads.
(2) increment or decrement the number of threads, performance test run in multiple experiments.
(3) determine the number of threads the most worry.

 

Guess you like

Origin www.cnblogs.com/dgwblog/p/11517910.html