|
| 1 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 2 | +import threading |
| 3 | +import requests |
| 4 | +import time |
| 5 | + |
| 6 | + |
| 7 | +def download_html(i): |
| 8 | + url = f'https://www.baidu.com/s?ie=UTF-8&wd={i}' |
| 9 | + response = requests.get(url).text |
| 10 | + return response |
| 11 | + |
| 12 | +ids = list(range(100)) |
| 13 | + |
| 14 | +# with ThreadPoolExecutor(max_workers=8) as exe: |
| 15 | +# exe.map(download_html,ids) |
| 16 | + |
| 17 | + |
| 18 | +# 其他接口使用: |
| 19 | +from concurrent.futures import ThreadPoolExecutor, as_completed,wait |
| 20 | + |
| 21 | + |
| 22 | +executor = ThreadPoolExecutor(max_workers=8) |
| 23 | + |
| 24 | +# 通过 submit 提交执行的函数到线程中 |
| 25 | +task1 = executor.submit(download_html, (1)) |
| 26 | +task2 = executor.submit(download_html, (3)) |
| 27 | + |
| 28 | +# done() 判断 task 是否完成 |
| 29 | +print(task1.done()) |
| 30 | +time.sleep(4) |
| 31 | +print(task1.done()) |
| 32 | + |
| 33 | +# result() 获取 task 的执行结果 阻塞 |
| 34 | +print(task1.result()) |
| 35 | + |
| 36 | +# cancel() 取消任务,如果任务在执行中或者执行完了是不能取消的 |
| 37 | +# 现在线程池是8 两个任务都会被提交任务去执行,如果 max_workers = 1,执行task2.cancel()就会成功取消 |
| 38 | +print(task2.cancel()) |
| 39 | + |
| 40 | + |
| 41 | +# as_completed() 获取已经成功的task的返回数据,阻塞 |
| 42 | +# as_completed实际上是一个生成器,里面有 yield 会把已经完成的 future (task) 返回结果 |
| 43 | +ids = list(range(10)) |
| 44 | +all_task = [executor.submit(download_html,(i)) for i in ids] |
| 45 | +time.sleep(8) |
| 46 | +# 这是异步的,谁完成就处理谁 |
| 47 | +for future in as_completed(all_task): |
| 48 | + data = future.result() |
| 49 | + print(f'html response {data}') |
| 50 | + |
| 51 | + |
| 52 | +# 通过 executor 获取已经完成的task |
| 53 | +for data in executor.map(download_html,ids): |
| 54 | + print(f'html response {data}') |
| 55 | + |
| 56 | + |
| 57 | +# wait() 等待task完成 |
| 58 | +ids = list(range(10)) |
| 59 | +all_task = [executor.submit(download_html,(i)) for i in ids] |
| 60 | + |
| 61 | +# wait 的 return_when 可选项 |
| 62 | +FIRST_COMPLETED = 'FIRST_COMPLETED' |
| 63 | +FIRST_EXCEPTION = 'FIRST_EXCEPTION' |
| 64 | +ALL_COMPLETED = 'ALL_COMPLETED' |
| 65 | +_AS_COMPLETED = '_AS_COMPLETED' |
| 66 | + |
| 67 | +wait(all_task, return_when=ALL_COMPLETED) |
0 commit comments