为多个函数正确实现(并发)asyncio

2023-12-12

我有几个函数,它们的执行并不相互依赖。我想做的是同时执行它们而不是顺序执行(同步)。我也添加了事件循环,但我无法确定它是否正常工作。

这是实现:

File 1:

import file2

def funcA():
    a, b = 1, 2
    file2.main(a, b)

File2:

def main(a, b):
    asyncio.get_event_loop().run_until_complete(_main(a, b))

async def _main(a, b):
     out1 = await funcA(a, b)
     out2 = await funcB(a, b)
     out3 = await funcC(a, b)

async def funcA(a, b):
    result = 1 # some processing done here
    return result

async def funcB(a, b):
    result = 1 # some processing done here
    return result

async def funcC(a, b):
    result = 1 # some processing done here
    return result

我无法弄清楚这些是否同时工作。我正在添加time.sleep(10)在任何函数中,执行都会停止。我不希望它们像我一样在后台运行需要这些函数的输出.


做你想做的事情的一种方法是使用asyncio.run() in main进而gather在 main 的异步版本中。要模拟长时间处理,请使用asyncio.sleep()请看下面的代码:

import asyncio

def main(a, b):
    res = asyncio.run(async_main(a, b))
    print(f"in main, result is {res}")

async def funcA(a, b):
    print('funcA - start')
    await asyncio.sleep(3)
    result = (a+b) # some processing done here
    print('funcA - end')

    return result

async def funcB(a, b):
    print('funcB - start')
    await asyncio.sleep(3)
    result = (a+b)*2 # some processing done here
    print('funcB - end')
    return result

async def funcC(a, b):
    print('funcC - start')
    await asyncio.sleep(3)
    result = (a+b)*3 # some processing done here
    print('funcC - end')

    return result

async def async_main(a, b):
    print("in async_main")
    res = await asyncio.gather(funcA(a, b), funcB(a, b), funcC(a, b))
    print(f"in async_main, result is {res}")
    return res

if __name__ == "__main__":
    main(1, 2)

结果是:

in async_main
funcA - start
funcB - start
funcC - start
funcA - end
funcB - end
funcC - end
in async_main, result is [3, 6, 9]
in main, result is [3, 6, 9]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为多个函数正确实现(并发)asyncio 的相关文章

随机推荐

  • 预期语句 End If

    我在表单中设置了以下代码 但收到 预期语句 错误 我第一次这样做并认为我的语法正确 我错过了什么 使用嵌套 2 路条件时 每个条件必须由自己的条件结束End If If condition A Th
  • 在define_method中使用局部变量

    我想了解如何define method工作原理以及如何正确使用定义块之外的变量 这是我的代码 class Test def self plugin for i in 1 2 define method test i to sym do p
  • 存储过程获取想要的结果集以提高性能-MYSQL

    我对 mysql 完全陌生 正在努力编写存储过程来获取所需的结果集 正如你所看到的 下面是我的表格 我在用着节点和快车要连接的 APImysql数据库 然后我使用以下命令进行单独查询以获得所需的结果for loop 当我处理数百万条记录时
  • Salesforce对象描述有大数据,如何从Salesforce对象描述中获取有限的数据,例如选项列表值

    我正在寻找获取销售人员对象的字段和选项列表的方法 我可以使用 REAT API 调用来完成此操作 describe在对象名称之后 但有时返回的 JSON 数据非常大 其中有 95 的额外数据是我不想要的 并且带有重复的模式字符串 仅仅为了获
  • 锚标记的 onclick 事件上未定义 Javascript 函数

    我无法访问锚标记的 onclick 事件中的 javascript 函数 在某些情况下它有效 而在某些情况下则无效 任何人都可以说出为什么会发生这种情况吗 HTML 代码 a href class btn waves effect wave
  • ggplot2 饼图和圆环图在同一图上

    I am trying to replicate this with R ggplot I have exactly the same data browsers lt structure list browser structure c
  • SAS 宏,将值作为字符串传递给 where 子句

    我下面有一个 SAS 宏不起作用 此代码片段不返回任何值 因为 where 语句不起作用 有人有主意吗 我尝试添加 str 但这也不起作用 macro refreshments beverage type proc sql select w
  • WPF DataGrid 性能 - 筛选性能

    我们正处于将应用程序从 SilverLight 转换为 WPF 的阶段 我们在其中开发了 我们自己的自定义 DataGrid 位于 Silverlight 的本机 DataGrid 之上 应用程序由大量视图组成 其中 近 99 的视图都在使
  • 如何在SQL中根据多个“标签”查询数据?

    我有三个简单的表 Items ItemID int PK ItemName nvarchar50 ItemCost int Tags TagID int PK TagName nvarchar50 ItemTags ItemID int F
  • Foreach 循环(或者 do while 可能?) - 只想根据页面返回一条记录

    使用下面编辑的代码解决了这个问题 感谢所有提供帮助的人 我的数据库中有两条记录 每条记录有 6 个字段 challengeId partnerName code challengeTitle description image url 我从
  • 解析 CSV 文件并聚合值、多列

    我想修改这里的帖子 解析 CSV 文件并聚合值 对多列而不是一列求和 所以对于这些数据 CITY AMOUNT AMOUNT2 AMOUNTn London 20 21 22 Tokyo 45 46 47 London 55 56 57 N
  • 使用reduce 或join 组合数组有什么区别?

    考虑以下字符串数组 let arrayStrings H e l l o 为了组合它的元素 将 Hello 作为单个字符串 我们可以 reduce it let reducedString arrayStrings reduce 0 1 H
  • 如何在 Ajax 调用中添加 UI 旋转器?

    我想在 Ajax 调用上显示加载微调器 我试过spin js图书馆 但它不起作用 这是我的 JavaScript 函数 它使用 Ajax 调用 function sendRequest ajax url spinner type get c
  • 如果剧集直接连续或重叠,则合并日期行

    我有一个这样的表 ID BEGIN END 如果同一 ID 存在重叠剧集 例如2000 01 01 2001 12 31 and 2000 06 01 2002 06 31 我想使用合并行MIN BEGIN MAX END 如果剧集是直接连
  • 单击键盘中的“完成”按钮时如何调用方法?

    我想在 UITextField KeyBoard 中单击 完成 按钮时调用一个方法 请帮我 甚至没有必要实现委托 我非常喜欢使用良好的老式目标 操作模式来处理这个问题 如果您有多种结束编辑的方法 例如 拦截文本字段外部的触摸以取消编辑 它还
  • 根据 Avalonia 中的 DataContext 属性选择 DataTemplate

    我正在实现一个 UserControl 它应该显示设置列表 public class SettingPropertyItem string Name get Type ValueType get object Value get set 基
  • 我无法安装 Netbeans10

    作为一个java初学者 我发现安装Netbeans8很容易 但安装Netbeans10却很困难 似乎我需要处理我下载的文档 这是Netbeans网站上的说明 但我不明白为什么我不能安装它 请帮我知道如何处理它 要从源代码构建 Apache
  • LinkedIn API 中的目标受众计数

    LinkedIn API v1 有一个 API 端点来计算所选目标受众的数量 后面的api只有这个端点Ads API 现在 我尝试使用定位标准来分享帖子 分享API 我想限制发帖的受众人数少于300人 由于LinkedIn有限制 受众人数必
  • 检测 Xamarin Scrollview 何时到达末尾

    我正在使用 xamarin 表单在滚动视图中显示项目列表 我想添加一个功能 以便当用户滚动到页面底部时我可以触发一个事件 例如加载更多项目 目前 我正在使用此 OnScrolled 函数来触发加载事件 private void OnScro
  • 为多个函数正确实现(并发)asyncio

    我有几个函数 它们的执行并不相互依赖 我想做的是同时执行它们而不是顺序执行 同步 我也添加了事件循环 但我无法确定它是否正常工作 这是实现 File 1 import file2 def funcA a b 1 2 file2 main a