电脑:win7 64位旗舰版
Python:3.8.1
pycharm:PyCharm 2022.3 (Community Edition)
为避免反复创建和销毁线程,所以使用线程池。但是线程池只能在创建时和提交前确定池中数量,不能在提交以后修改池中数量。
pool = concurrent.futures.ThreadPoolExecutor(2) print(pool,type(pool)) def task(i): with open("d:\\1\\"+str(i)+".txt",mode="wb") as f: f.write(bytes(1024*1024*100)) return i,".txt 结束" def call_callback(res:concurrent.futures.Future): print(res.result()) # if i==2: # pool._max_workers=8 pool._max_workers=4 for i in range(26): pool.submit(task,i).add_done_callback(call_callback)
上面代码创建时设置池中数量是2,提交前修改数量为4,。运行代码发现文件夹下第一次同时生成的是4个TXT。说明修改生效。
call_callback()函数中的 if 语句没效果,说明运行中修改不好使。