后浪小萌新Python --- 线程池

tech2024-08-08  46

线程池

自动创建线程并且自动安排每个线程的任务

from threadpool import ThreadPool, makeRequests from threading import Thread import time # 1. 创建线程池对象 # ThreadPool(线程数) - 创建线程池对象,并且设置线程数(线程是线程池自动去创建的) pool = ThreadPool(100) # 2.确定任务对应的函数 def down_load(url): time.sleep(3) print(url) # 3.创建任务列表 # 创建任务对象: makeRequests(任务对应的函数, 任务函数调用的时候传递的实参列表) urls = [f'https://{x}' for x in range(200)] requests = makeRequests(down_load, urls) # 4.将每个任务添加到线程池中 for re in requests: pool.putRequest(re) # 开始执行任务,并且等待所有任务都执行完成 def finish(): pool.wait() print('所有电影下载完成:========================') t = Thread(target=finish) t.start()

执行结果:

https://0 https://43https://44https://41 https://37 https://36https://31https://30 https://27https://25https://23https://29 https://21https://15https://13https://17https://11 https://8https://7 https://3https://1https://24 https://20 https://39 https://35 https://14 https://99https://97 https://10https://96https://85https://40 https://6https://81https://79 https://78https://77https://75https://51https://38https://2https://50 https://22 https://18 https://12 https://95 https://93 https://92https://90https://88 https://28 https://84https://83 https://82 https://4 https://26 https://73https://71 https://68 https://66 https://63 https://61https://59https://57 https://54 https://49https://48 https://47 https://19https://33 https://94 https://89 https://86 https://42 https://80 https://74 https://69 https://65https://62 https://58 https://55 https://45https://46 https://16 https://9 https://91 https://5https://76 https://72https://70 https://56https://53https://52 https://98 https://87 https://64 https://34https://32 https://67https://60 https://100 https://105https://103https://101https://106 https://102 https://104 https://115 https://116 https://112 https://110 https://108 https://113https://111 https://109 https://107 https://114 https://125https://126 https://124https://117 https://122 https://119 https://123 https://121 https://120 https://118https://135https://136https://137 https://134https://131 https://129 https://127 https://128https://133 https://130 https://132 https://149https://150https://147https://143https://141 https://138https://145https://146https://142 https://148 https://140 https://139 https://144 https://171https://168https://167https://165 https://164https://161https://160https://159https://158https://157https://156 https://155 https://170 https://172https://162 https://154https://153 https://163 https://169 https://152https://151https://166 https://199https://196https://194https://192https://188https://189 https://186https://183 https://178https://176https://174https://181https://187 https://198 https://193 https://180https://195 https://191https://197 https://190 https://185https://184 https://177 https://173 https://182 https://175 https://179 所有电影下载完成:========================
最新回复(0)