Two methods submit and map the thread pool
from concurrent.futures import ThreadPoolExecutor import time # def sayhello(a): time.sleep(2) return "hello: "+a def main(): seed = ["a","b","c"] # 不使用线程 start1 = time.time() for each in seed: t1 = sayhello(each) print(T1) END1 = the time.time () Print ( " TIME1: " + STR (end1- Start1)) Print ( ' ------------------ Submit ---- ------------------ ' ) # thread pool usage submit # 1 value is stored in the first list # 2 takes the return value in the traversal list # 3 will be acquired traverse the result is stored in the list start2 = the time.time () LST = [] result_lst = [] with the ThreadPoolExecutor ( . 3 ) AS Executor: for each in SEED: T2 =executor.submit (sayHello, each) lst.append (T2) for I in LST: Print (i.result ()) result_lst.append (i.result ()) Print (result_lst) end2 = the time.time () Print ( " TIME2: " + STR (end2- start2)) Print ( ' --------------- Map ------------------- --- ' ) # usage map of the thread pool # parameters of the map: iterator # map the return value: generator # 1, generator acquires (or directly attached to force transducers list) # 2, traversal value #3, the traversal results into a new list map_lst = [] start3 = the time.time () with the ThreadPoolExecutor ( 3 ) AS executor1: T3 = executor1.map (sayHello, SEED) for T in T3: map_lst.append (T ) Print (map_lst) END3 = the time.time () Print ( " time3: " + STR (end3- start3)) IF the __name__ == ' __main__ ' : main ()
the difference
the Map: 1 , submitted by the task function is the same as 2 parameters: only need to submit one objective function, parameter objective function in an iterator (lists, dictionaries) the Submit: 1 , submitted by the task function is not the same, or abnormalities that may occur in the process of execution (using a process map to identify problems in the implementation of a direct throw an error) 2 , parameter: submit every parameter required to submit an objective function and the corresponding results: map can guarantee the order of output, submit output the order is chaos