协程封装使用
await、async出来有一阵时间了,之前一直没有用到,这次工作中有需要用的,就赶快上网查查,怎奈大多都是互相抄袭理论知识,相同案例并无实际作用,本人也是浏览了很多相关帖子等,最后也是找到了一些参考,最后再自己封装成一个可直接调用类,方便后期使用。
关于理论知识本人就不打字了,网上很多嘛,大家懂得
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 # __author__ = '北方姆Q' 4 5 6 import asyncio 7 8 9 class Asyncio(object): 10 def __init__(self, funcs): 11 self.loop = asyncio.new_event_loop() 12 self.funcs = funcs 13 asyncio.set_event_loop(self.loop) 14 15 try: 16 self.results = self.loop.run_until_complete(self.gather_tasks()) 17 finally: 18 self.loop.close() 19 20 async def gather_tasks(self): 21 tasks = (self.make_future(func, *args) for func, *args in self.funcs) 22 results = await asyncio.gather(*tasks) 23 return results 24 25 async def make_future(self, func, *args): 26 future = self.loop.run_in_executor(None, func, *args) 27 response = await future 28 return response 29 30 31 def task1(x, y, z): 32 return x + y + z 33 34 35 def task2(z): 36 return z 37 38 39 my_list = ( 40 (task1, 1, 2, 3), 41 (task2, 10), 42 ) 43 obj = Asyncio(my_list) 44 print(obj.results)