Go lang中的Python asyncio事件循环等效项

时间:2018-11-11 15:36:37

标签: python-3.x asynchronous go concurrency python-asyncio

我在 Python3.x 中使用异步/并发asyncio事件循环。

在Go lang中是否存在与<{>}相当的asyncio或协程,并且使用线程具有并发性能?


[注意]:

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


[更新]:

下面是使用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())

出局:

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

在Go中不需要此功能,因为在Go中这将是反模式。

相反,在Go中,您可以管理"pollable" descriptors(例如套接字),并与运行时和goroutine调度程序紧密集成。 这样,您就可以编写普通的顺序代码,这些代码将通过特定于平台的“事件”接口在内部进行处理(例如,Linux上的epoll,FreeBSD上的kqueue和IOCP上的IOCP视窗)。 一旦goroutine尝试在套接字上执行任何I / O并且套接字尚未准备好,goroutine就会被挂起,直到该数据准备好为止,之后它将在挂起的位置立即恢复。

因此,在Go中,您仅创建一个单独的goroutine来处理应与其他请求同时执行或同时处理的每个请求,并编写简单的顺序代码来处理该请求。

对于backrgound,请启动herehere

解释Go调度程序工作原理的教程是 例如thisthis

答案 1 :(得分:1)

用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等效的文件。