Issue
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.
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.