Go lang 中的 Python asyncio 事件循环等价物

标签 python go asynchronous concurrency python-asyncio

我使用 asyncio 事件循环,这是一种在 Python3.x 中执行异步/并发任务的方法。

Go 语言中是否有任何等同于asyncio(async/await)或协程的线程


[注意]:

不是并行 + 并发(多处理)模式。


[更新]:

这里是一个使用 Python 中的 asyncio 的异步事件循环,以便更好地理解:

import asyncio
import time

async def async_say(delay, msg):
    await asyncio.sleep(delay)
    print(msg)

async def main():
    task1 = asyncio.ensure_future(async_say(4, 'hello'))
    task2 = asyncio.ensure_future(async_say(6, 'world'))

    print(f"started at {time.strftime('%X')}")
    await task1
    await task2
    print(f"finished at {time.strftime('%X')}")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

输出:

started at 13:19:44
hello
world
finished at 13:19:50

如有任何帮助,我们将不胜感激。

最佳答案

在 Python 术语中,事件循环是内置 Go 的。您将使用 go async_say(...) 启动两个 goroutine 并等待它们完成,例如使用 channelwait group .

将您的代码直接转换为 Go 可能如下所示:

package main

import "fmt"
import "time"

func async_say(delay time.Duration, msg string, done chan bool) {
    time.Sleep(delay)
    fmt.Println(msg)
    done <- true
}

func main() {
    done1 := make(chan bool, 1)
    go async_say(4 * time.Second, "hello", done1)
    done2 := make(chan bool, 1)
    go async_say(6 * time.Second, "world", done2)
    <-done1
    <-done2
}

请注意,与 Python(和 JavaScript 等)不同,Go 函数不会以不同的方式出现 colors取决于它们是否异步。它们可以全部异步运行,标准库中内置了 asyncio 的等价物。

关于Go lang 中的 Python asyncio 事件循环等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53250293/

相关文章:

javascript - 在通过 setTimeout 或 promise 阻止代码之前更新 DOM

python - 将标准输出转换为字符串

linux - 为什么在 golang、linux 中使用 archive/zip 时文件名会变得困惑?

mysql - 从迁移创建存储过程

go - 使用 go-flags 的命令的全局参数

javascript - 异步运行两个 Promise,但优先考虑第一个 Promise 的结果

asynchronous - 如何测量 Julia 中函数的@async 运行时间?

python - 使用字典将 "sequential"信息添加到 python 列表

python - 康威的生命游戏不会运行 Python

python - 防止 lxml 创建自闭合标签