Mahdi.Kh
November 23, 2026
We see what a goroutine really is, why it is so much cheaper than a thread, and how to wait for goroutines, collect their results and stop them cleanly.
Picture the page a user lands on right after signing in: their profile, their latest orders, a few notifications. Each piece comes from a different service, and each service takes a moment to answer. Written the obvious way, the page asks for the profile and waits, asks for the orders and waits, asks for the notifications and waits. The user sits through the sum of all three, although the three questions have nothing to do with each other.
Goroutines are how Go lets those calls happen at the same time. In this part, the first one after the introduction, we look at what a goroutine really is, why it is so much cheaper than a thread, how to wait for goroutines and get their results back, and the handful of mistakes nearly everyone makes in their first week with them.
A goroutine is a function call that runs independently of the code that started it. You start one by putting go in front of the call:
The go statement evaluates the arguments right away, starts the call in a new goroutine and returns immediately. It does not wait, and it gives you nothing back: no return value, no handle, no ID. If you want a result, or want to know when the goroutine is finished, the goroutine has to tell you, and most of this series is about the ways it can. main itself runs in a goroutine too, the first one every program has.
If processes and threads feel a little hazy, the Goroutines post of our Golang basics series builds them up from scratch. Here the short version is enough. An operating system thread is a heavy thing: the kernel manages it and reserves a stack of a megabyte or more for it up front. A goroutine belongs to Go's runtime instead. It starts with a stack of a few kilobytes that grows only when it needs to, and starting one costs little more than a function call. A program with a hundred thousand goroutines is ordinary; a program with a hundred thousand threads is in trouble.
The runtime's scheduler runs all those goroutines on a small number of threads. At any moment at most GOMAXPROCS threads are running Go code, by default one per CPU core. The trick is what happens when a goroutine has to wait, for a timer, the network or another goroutine: the scheduler sets it aside and gives the thread to a goroutine that is ready. When the wait is over, the goroutine joins the line of ready ones again and soon gets a thread back.
Think of a small kitchen with two cooks and a rail full of order tickets. A cook does not stand in front of the oven while a pizza bakes; they slide it in and take the next ticket. When the oven beeps, the pizza's ticket goes back on the rail and whichever cook is free finishes it. The cooks are threads, and the tickets are goroutines.
In the diagram above, two threads are busy and six goroutines are ready to run. Three more are waiting: on a timer, on the network and on a channel. None of the waiting ones holds a thread, which is why waiting is so cheap in Go, and why ten thousand goroutines waiting for network replies can share a couple of threads. Since Go 1.14 the scheduler can also interrupt a goroutine that computes for a long time without ever waiting, so one busy loop cannot starve the rest.
The same picture shows the difference between concurrency and parallelism. With one thread, the goroutines would still take turns and make progress together; that is concurrency. With two threads, two of them really run at the same instant; that is parallelism. Your code is the same in both cases.
Let's build the sign-in page from the opening, with time.Sleep standing in for the calls to the other services. The program loads the three parts one after another, then all at once, and times both:
The first loop is ordinary code. The second starts each call in its own goroutine, and three small things make it work:
go func() { ... }() starts the function literal and the loop moves straight on.sync.WaitGroup is a counter we can wait on: wg.Add(1) before each go, defer wg.Done() as the first line inside the goroutine, and wg.Wait() blocks until the counter is back to zero. The WaitGroup part looks at it closely; this three-line shape is all we need for now.p. Since Go 1.22 every iteration of a for loop has a fresh variable, so each closure captures the part of its own iteration. We come back to this among the mistakes.The output looks like this:
One after another, the page takes the sum of the three, a little over 80 + 120 + 200 = 400 ms. All at once, it takes as long as the slowest part, 200 ms. Look at the order of the second block too: it follows how long each part took, not the order of the loop. When two goroutines finish at almost the same moment, which one prints first can change from run to run. Never rely on the order in which goroutines happen to run; when order matters, arrange it yourself, as the next example does.
A goroutine has no return value, so how does each call hand the page its data? When you know up front how many goroutines you will start, the simplest safe answer is to give each one its own slot to write in:
A few details carry the whole program:
results has one element per name and is created before any goroutine starts. Goroutine i writes only results[i]. Different elements of a slice are different variables, so no two goroutines ever touch the same memory, and that is what keeps this free of data races.wg.Wait() does more than wait. Once it returns, everything the goroutines wrote before their Done is visible to main. Reading results before Wait returns would be a race.names, whichever goroutine finished first, because the order lives in the slots and not in the timing.errors.Join turns any number of errors into one (see Error Handling for the basics).Four calls of 100 ms each took 100 ms in total. This one-slot-per-goroutine shape covers a surprising number of real cases. When you don't know the count in advance, or want each result the moment it is ready, you need a channel, which is where the next part picks up.
The goroutines so far ended on their own: they made one call and returned. Plenty of goroutines are not like that. An editor saves your draft every few seconds, a server flushes its metrics, a cache throws out old entries; each of these loops for as long as the program needs it. Go has no way to kill a goroutine from outside, so a long-running goroutine has to be asked to stop, and it has to listen for the request.
The standard way to ask is a context.Context (a quick refresher is in the Context post; the Context part of this series goes much further). Here is an autosaver that runs until the editor closes:
Three habits are worth copying from it:
autosave is an ordinary function that runs until its context is cancelled. It does not start a goroutine and does not know it is in one; the caller decides that with go. Functions written this way are easier to test and to reuse.cancel() asks the goroutine to stop, and wg.Wait() waits until it really has. You need both: cancelling without waiting lets main exit in the middle of a save, and waiting without cancelling waits forever.defer cancel() right after creating the context releases it on every way out of the function, even if we forget the explicit call.Notice that autosave sees the cancellation only when it wakes up from its sleep, up to 100 ms later. In the select statement part we will let a goroutine wait for its timer and for ctx.Done() at the same time, so it stops the moment it is asked.
Run it and the only line you get is main: done. The three goroutines were started, but when main returns the program exits, and every other goroutine ends with it, in the middle of its work and without a word. Without the 10 ms of work you would sometimes see a line or two slip out, which is worse: a bug that shows up only sometimes. A time.Sleep in main is not a fix either, only a guess. Wait for them properly, with a sync.WaitGroup as above or by receiving their results.
Nothing guarantees that any goroutine has reached its Add before main reaches Wait. If none has, the counter is still zero and Wait returns at once. Call Add in the goroutine that will call Wait, before the go statement. Newer Go versions add wg.Go(func() { ... }), which does the Add and the Done for you.
Before Go 1.22 a loop had one variable for all its iterations, and the classic bug was a set of goroutines that all saw its last value:
Go 1.22 gave every iteration its own variable, so this now prints 0, 1 and 2 in some order, and the i := i lines you find in older code can go. One catch: the new behaviour follows the go line of your module's go.mod, so a module that still says go 1.21 keeps the old one.
What has not changed is that a closure captures variables, not their values. A goroutine that reads a variable while another goroutine writes it is a data race:
The goroutine may print either value, and with a data race the language promises nothing at all, not even one of the two. Pass the value as an argument, go func(status string) { ... }(status), or simply don't share it. Run your tests with go test -race as well: the race detector catches these while the code runs. Protecting state that really has to be shared is the subject of the Mutex and RWMutex part.
A goroutine that waits for something that never comes, a value nobody sends, a lock nobody releases, a context nobody cancels, stays blocked forever. The garbage collector does not collect blocked goroutines, so each one keeps its stack and everything it points to. That is a goroutine leak, and in a server that leaks one per request it shows up as memory that only ever grows. Here is the classic shape, borrowing a channel from the next part:
The function returns with the first answer, and every other goroutine waits forever to hand over its own. The habit that prevents leaks is simple to state: before you write go, know how that goroutine is going to end. The next two parts give us the tools for it, and we will fix this very function along the way.
net/http, for example, already serves every request in its own goroutine.go f() starts f in a new goroutine and returns at once, with no result and no handle.main returns, the program ends: wait for your goroutines, with Add before go and defer wg.Done() inside.-race.go, know how the goroutine will stop.In the next part we give goroutines a way to talk to each other: channels.
Previous part: Introduction | Concurrency in Go
Next part: Channel Fundamentals | Concurrency in Go