Python asyncio event loop equivalent in Go lang

Question:

I use asyncio event loop which is a kind of performing asynchronous/concurrency tasks in Python3.x .

Is there any equivalent of asyncio (async/await) or coroutines in Go lang on a thread only?


[NOTE]:

Not parallelism + concurrency (multiprocessing) pattern.


[UPDATE]:

Here is an asynchronous event loop using asyncio in Python for better sense:

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())

Out:

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

Any help would be greatly appreciated.

Answers:

You don’t need this in Go as in Go this would be an anti-pattern.

Instead, in Go, you have management of “pollable” descriptors — such as sockets — tightly integrated with the runtime and the goroutine scheduler.
This allows you to write normal sequential code which will internally be handled via a platform-specific “eventful” interface (such as epoll on Linux, kqueue on FreeBSD and IOCP on Windows).
As soon as a goroutine tries to perform any I/O on a socket and the socket is not ready, the goroutine gets suspended until that data is ready after which it will be resumed right at the place it has been suspended.

Hence in Go, you merely create a separate goroutine to serve each request which should be performed or served concurrently with the others and write plain sequential code to handle it.

For backrgound, start here and here.

The tutorials explaining how the Go scheduler works are,
for instance, this
and this.

Answered By: kostix

In Python terms, the event loop is built into Go. You would launch two goroutines with go async_say(...) and wait for them to complete, for example using a channel or a wait group.

A straightforward translation of your code to Go could look like this:

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
}

Note that, unlike Python (and JavaScript, etc.), Go functions do not come in different colors depending on whether they are asynchronous or not. They can all be run asynchronously, and the equivalent of asyncio is built into the standard library.

Answered By: user4815162342