# Gist of Go: Goroutines ![rw-book-cover](https://antonz.org/go-concurrency/goroutines/cover.png) ## Metadata - Author: [[Anton Zhiyanov]] - Full Title: Gist of Go: Goroutines - Category: #articles - Summary: The text explains how to count digits in words using goroutines and channels in Go. It outlines a method to create separate goroutines for processing words and counting digits, improving concurrency. The final solution involves using named functions to handle word submission, counting, and filling statistics efficiently. - URL: https://antonz.org/go-concurrency/goroutines/ ## Highlights - The Go runtime juggles these goroutines and distributes them among operating system threads running on CPU cores. Compared to OS threads, goroutines are lightweight, so you can create hundreds or thousands of them. ([View Highlight](https://read.readwise.io/read/01jv2qgyvm48b4qmba7zs5a6cw)) - The main function is also a goroutine, but it starts implicitly when the program starts. So we have three goroutines: `main`, `say(1)`, and `say(2)`, all of which are independent. The only catch is that when `main` ends, everything else ends too. ([View Highlight](https://read.readwise.io/read/01jv2qhw1vcapqvzv8j9jqpfve)) - In Go, it's common to separate concurrency logic from business logic. This is usually done with separate functions. In simple cases like ours, even anonymous functions will do: ([View Highlight](https://read.readwise.io/read/01jv2qvkcmha8f6w3vn127j4zq)) - So, channels not only transfer data, but also help to synchronize independent goroutines. This will come in handy later. ([View Highlight](https://read.readwise.io/read/01jv2vfrb8rgnt3xrfwcwqjrbr)) - ┌─────────────┐ ┌─────────────┐ │ goroutine A │ │ goroutine B │ │ └────┘ │ │ X <- chan <- X │ │ ┌────┐ │ │ │ │ │ └─────────────┘ └─────────────┘ ([View Highlight](https://read.readwise.io/read/01jv2vdawd4323x15k9khpjjtr)) - For more complex tasks, it's useful to have a goroutine for reading data (*reader*) and another for processing data (*worker*). Let's use this approach in our function: ┌───────────────┐ ┌───────────────┐ │ sends words │ │ counts digits │ ┌────────────────┐ │ to be counted │ → (pending) → │ in words │ → (counted) → │ fills stats │ │ │ │ │ └────────────────┘ └───────────────┘ └───────────────┘ reader channel worker channel outer function ([View Highlight](https://read.readwise.io/read/01jv2xsesphff4pe6zhq43p84r)) - Returning an output channel from a function and filling it within an internal goroutine is a common pattern in Go. ([View Highlight](https://read.readwise.io/read/01jv2z2050fdfz09z2h9gd7j5y))