concurrent.futures usage and analysis

from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED
from concurrent.futures import Future
from multiprocessing import Pool

#Future object, task's return container


#Thread pool, why thread pool # The status of a thread or a task can be obtained in the main thread, as well as the return value 
# When a thread is completed 
, our main thread can immediately know 
# futures can allow multi-threading and multi- tasking The process coding interface is consistent with the import time


def get_html(times):
    time.sleep(times)
    print("get page {} success".format(times))
    return times



executor = ThreadPoolExecutor(max_workers=2 )
 #Submit the executed function to the thread pool through the submit function, and submit returns immediately 
# task1 = executor.submit(get_html, (3)) 
# task2 = executor.submit(get_html, (2) )


#To get the return urls of successful tasks 
= [3,2,4 ]
all_task = [executor.submit(get_html, (url)) for url in urls]
wait(all_task, return_when=FIRST_COMPLETED)
print("main")

# for future in as_completed(all_task): #Whoever completes first will print first 
#      data = future.result() 
#      print("get {} page".format(data))

#Get the value of the completed task through the executor's map, order 
# for data in executor.map(get_html, urls): 
#      print("get {} page".format(data))


# # The done method is used to determine whether a task is completed 
. # print(task1.done()) 
# print(task2.cancel()) 
# time.sleep(3) 
# print(task1.done())
#
# # The result method can get the execution result of the task 
# print(task1.result())

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326832264&siteId=291194637