我使用 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 并等待它们完成,例如使用 channel或 wait 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/