Ben*_*ari 0 concurrency asynchronous go python-3.x python-asyncio
我asyncio
在Python3.x 中使用异步/并发事件循环。
asyncio
在 Go lang 中是否有任何等效或协程具有使用线程的并发性能?
[注意]:
不是并行+并发(多处理)模式。
[更新]:
这是一个asyncio
在 Python 中使用的异步事件循环,以便更好地理解:
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())
Run Code Online (Sandbox Code Playgroud)
出去:
started at 13:19:44
hello
world
finished at 13:19:50
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。
在 Python 中,事件循环内置于Go 中。您将启动两个 goroutinesgo async_say(...)
并等待它们完成,例如使用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
}
Run Code Online (Sandbox Code Playgroud)
请注意,与 Python(和 JavaScript 等)不同,Go 函数不会根据它们是否异步而有不同的颜色。它们都可以异步运行,标准库中内置了 asyncio 的等价物。