Posted on
Learning Go: Why Goroutines Aren’t Just Coroutines
I have been learning Golang this week as it is going to be required in one of my upcoming projects. I came across a brilliant video by Alex Mux, which is perfect for developers experienced in another language who want to learn the syntax quickly as well as understand what makes Go unique and how to use it.
When introduced to Go routines, which is how Go handles concurrent functions, I was tempted to immediately treat it like a coroutine like in Python or JavaScript, but the similarities end pretty quickly.
Python and JavaScript both by design use only a single thread to execute bytecode and use an event loop mechanism to implement concurrency. Go by design isn’t limited in this way and can use all the cores of the machine with multiple threads.
The control flow i.e the pausing and resuming of concurrent functions is automatically handled by the Go runtime which preemptively interrupts them. In contrast, Python and JavaScript handles this manually with the await syntax as well as the event loop that controls when the coroutines are paused and what order they run in respectively.
The above makes writing an efficient concurrent API in Go smooth and straight forward whereas writing the same in Python or JavaScript is painful because I have to:
Classify the task as I/O bound or CPU bound, because CPU bound tasks block the thread and hence need a workaround with multiple processes.
Understand how the event loop affects ordering and specifics in Python (asyncio) and JavaScript
Manually handle pausing, resuming, awaiting and buffering the coroutines when all of this is native in Go.
Keep in mind that after all this effort, it still won’t come anywhere close to Go in performance :(
Hopefully, this experience of trying out a new programming language and comparing it with languages I’m already experienced in has made me a more well-rounded developer.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse