zoukankan      html  css  js  c++  java
  • 协程封装使用

    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)


  • 相关阅读:
    tcp/ip--百度百科
    Web service--百度百科
    .NET--百度百科
    ibatis--百度百科
    Struts2--百度百科
    spring--百度百科
    从头认识Spring-1.15 对SpEl的值的操作(1)-数值运算
    performSelector 方法的自己主动俘获特性
    图解WinHex使用入门
    LINQ使用与并行
  • 原文地址:https://www.cnblogs.com/bfmq/p/14036767.html
Copyright © 2011-2022 走看看