在固定线程池,批量调用异步函数,如何修改代码
from concurrent.futures import ThreadPoolExecutor, as_completed import time import random import queue import asyncio import threading def print_error(value): error = value() print("error: ", error) # 传入多个参数 async def work2(name,m): while True: cake = q1.get(timeout=3, block=False) # print("cake值:{}".format(cake)) if cake and int(cake) % 14 != 0: print("线程名{}-*-{}".format(name, cake)) await asyncio.sleep(3) # time.sleep(1) elif cake and int(cake) % 14 == 0: print("线程名{}--退出{}".format(name, cake)) return if q1.empty(): break # 线程池有多少就限制运行多少个线程,其他阻塞,直至有线程腾空出来,顺序式 async def main1(): start = time.perf_counter() new_loop = asyncio.get_event_loop() with ThreadPoolExecutor(3) as executor1: task_list = [ new_loop.run_in_executor(executor1, work2, i, 3) for i in range(7) ] await asyncio.gather(*task_list) end = time.perf_counter() print(f'总计耗时:{end - start}') if __name__ == '__main__': # 线程锁定义在全局,无需传入函数 lock = threading.Lock() # 创建队列 q1 = queue.Queue() for i in range(100): q1.put(i) asyncio.run(main1()) 问题描述:RuntimeWarning: coroutine 'work2' was never awaited handle = None # Needed to break cycles when an exception occurs. RuntimeWarning: Enable tracemalloc to get the object allocation traceback 要怎么修改才不会报错
17
收起
正在回答 回答被采纳积分+1
1回答
Python全能工程师
- 参与学习 人
- 提交作业 16233 份
- 解答问题 4470 个
全新版本覆盖5大热门就业方向:Web全栈、爬虫、数据分析、软件测试、人工智能,零基础进击Python全能型工程师,从大厂挑人到我挑大厂,诱人薪资在前方!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星