1. Goroutine and the go operator: the basic model
If you used to program only “in one line,” then concurrency looks like a promise from an ad: “press a button — and everything will get faster.” In practice, goroutines are needed not only (and not so much) for speed, but for convenient code organization: while one part of the program waits for disk or network, another part can do useful work. Concurrency is about several tasks moving forward in an interleaved way, while parallelism is about truly simultaneous execution on CPU cores.
In Go, concurrency is built into the language. The very fact that the go operator exists is like a sign on a door: “welcome to a world where event order is not a contract.” And that is normal: we simply need to learn how to write code that does not depend on a random execution order.
To make the motivation more concrete, imagine our training app (a hypothetical task tracker in the console): we want it to be able to print a hint “don’t forget to save your changes” a couple of seconds after startup, while the main code keeps working and printing the menu. This is exactly where a goroutine fits: the “reminder” lives separately, and the main execution flow is not blocked.
What a goroutine is: a “very light thread,” but it is managed by the runtime
The word goroutine is often explained as a “green thread” or a “lightweight thread.” That is a good analogy, but it is important not to confuse it with operating system threads. In Go, a goroutine is a unit of execution that is scheduled and started by the Go runtime, not by you manually through an OS API. That is why goroutines are cheaper to create and destroy than full OS threads, and why Go can keep thousands of goroutines without making it feel like the computer is about to take off and fly out the window.
A useful model (without unnecessary internal details) is this: you have many goroutines, and the runtime distributes them across a limited number of OS threads, which actually run on CPU cores. How much can “really run at the same time” depends on GOMAXPROCS (the maximum number of threads that Go uses to execute goroutines simultaneously).
A small diagram so you do not have to keep this in your head as an abstraction:
flowchart TD A[Your program] --> B[Many goroutines: G1, G2, G3...] B --> C[Go runtime scheduler] C --> D[Several OS threads] D --> E[CPU cores]
We need this diagram for one reason: when you write concurrent code, you do not directly control “who runs when.” You define the structure (what can be done independently), and the runtime decides the schedule.
Launch syntax: go f() — this is an operator, not magic
The most important rule of today’s lecture sounds boring, but saves hours of life: the go operator applies only to a function call. That is, after go there must be something like functionName(...) or func(){...}().
In Go this is called a go statement: a language operator that starts executing a function in a separate goroutine.
Here is the minimal example:
package main
import "fmt"
func hello() {
fmt.Println("hello from goroutine") // hello from goroutine
}
func main() {
go hello()
fmt.Println("main continues") // main continues
}
If you run this code as is, you will often see only "main continues". And that is not “because Go is broken,” but because the program may finish before the goroutine even has time to do anything. The process lifecycle here matters more than your expectations (we will discuss this in detail in the next section).
Now an example of what you cannot do:
package main
func main() {
// go 1 + 2 // not allowed: after go there must be a function call
// x := go f() // not allowed: go is not an expression, it does not "return" anything
}
This is a common beginner mistake: you want to “create a thread” as a value, put it into a variable, and then “manage it.” That does not work in Go: a goroutine is started, lives, ends — but by itself it is not an object that you hold in your hands as a “handle.”
3. The lifecycle of a goroutine and the main law about main
The lifecycle of a goroutine is simpler than it seems, but it has one “cruel” feature. A goroutine is born when you execute go someFunc(...). After that, the runtime scheduler decides when to give it CPU time. It runs until the function ends (or until return). And here is the main rule: when main ends, the process ends. And together with the process, all goroutines disappear, even if they were “still working” and were in the middle of something important.
Let’s look at this as clearly as possible:
package main
import (
"fmt"
"time"
)
func main() {
go func() {
time.Sleep(50 * time.Millisecond)
fmt.Println("goroutine finished") // most likely you will not see it
}()
fmt.Println("main finished") // main finished
}
Why does the phrase "goroutine finished" usually not appear? Because main prints its message and ends the program, without waiting for the background goroutine.
To see the message, you can “prop up” main with an artificial delay:
package main
import (
"fmt"
"time"
)
func main() {
go func() {
time.Sleep(20 * time.Millisecond)
fmt.Println("goroutine finished") // goroutine finished
}()
time.Sleep(50 * time.Millisecond) // demonstration, not a protocol
fmt.Println("main finished") // main finished
}
It is important to say this honestly: time.Sleep(...) in main is not “proper waiting,” but a demonstration crutch. It is convenient for seeing the effect and feeling concurrency with your hands. But building program correctness on top of it is roughly like repairing a car with duct tape: it may get you there sometimes, but it is better not to rely on it.
4. Arguments, pointers, and results: what really happens at launch time
The moment arguments are evaluated: first we compute them, then we launch
This section seems minor, but it comes up all the time in real code. In Go, call arguments are evaluated before the goroutine starts. That is, first the values you passed to the function are computed, and only then is the goroutine created, receiving the already prepared arguments.
Example:
package main
import (
"fmt"
"time"
)
func printVal(v int) {
fmt.Println("v =", v)
}
func main() {
x := 1
go printVal(x) // argument x is evaluated here while x == 1
x = 2
time.Sleep(10 * time.Millisecond)
}
The output will be:
v = 1
And that is logical: we passed value 1 into printVal(...).
Now let’s compare this with passing a pointer (you already know &x and *p from the pointers topic). Here we are not passing a “snapshot of the number,” but the “address where the number lives,” and then the goroutine will see the current value at read time:
package main
import (
"fmt"
"time"
)
func printPtr(p *int) {
fmt.Println("*p =", *p)
}
func main() {
x := 1
go printPtr(&x) // pass the address
x = 2
time.Sleep(10 * time.Millisecond)
}
The output will most often be:
*p = 2
The phrase “most often” is not accidental here: concurrency adds nondeterminism. In one run, the goroutine may manage to read x before the assignment x = 2, in another run — after. And that is no longer about syntax, but about a fundamental idea: execution order between goroutines is not guaranteed unless you explicitly coordinate it.
You cannot “return a result” from a goroutine with an ordinary return
At some point almost every beginner tries to do this: “I’ll launch go compute(), and then somehow I’ll get the result.”
The problem is that a goroutine is launched by the go operator, and this operator has no “place” to store return values. Even if the function returns (int, error), those values will simply be ignored.
This can be shown with a simple example:
package main
import "fmt"
func compute() int {
return 42
}
func main() {
go compute() // the result is simply lost
fmt.Println("running...") // running...
}
The compiler does not complain because the function call is valid. But the meaning of the result disappears, like a sock after washing: it was there — and then it was gone.
At today’s level, the correct conclusion is this: goroutines are convenient for background tasks that produce side effects (printing, logging, writing to a file, a network request inside a handler, etc.) or change state according to a prearranged protocol. How exactly to “transfer results” between goroutines is a separate big topic, and we will not jump ahead.
5. Practice: a background reminder in a mini application
Let us take a small step toward practice and add background reminders to a hypothetical console task app. Suppose we have a “task of the day,” and after a short time the program will remind us about it without blocking the main flow.
package main
import (
"fmt"
"time"
)
func remind(task string) {
time.Sleep(30 * time.Millisecond)
fmt.Println("reminder:", task) // reminder: drink water
}
func main() {
task := "drink water"
go remind(task)
fmt.Println("menu: [1] list [2] add [0] exit") // menu: [1] list [2] add [0] exit
time.Sleep(50 * time.Millisecond) // demonstration
}
What is important here, besides the obvious go remind(task)?
We passed the string task by value. Strings in Go behave like “immutable data” from the user’s point of view, so this example is safer for demonstration: we do not have shared mutable memory that two goroutines modify at the same time.
And once again: Sleep at the end is only there so that we can see the reminder output. In a real program, you almost never want to “wait at random.”
6. panic inside a goroutine and local recover
This point is extremely important, because concurrency makes errors more “spectacular.” If a panic happens inside a goroutine, then by default it brings down the entire process when the panic reaches the top of that goroutine’s stack.
So “it crashed in the background” is not “well, it’s background anyway.” No, it is “the application terminated, thanks everyone.”
Example:
package main
import (
"fmt"
"time"
)
func main() {
go func() {
panic("boom")
}()
time.Sleep(10 * time.Millisecond)
fmt.Println("still alive?") // most likely you will not see it
}
For a goroutine not to bring down the entire process, recover must be done in that same goroutine and in a deferred function (defer). recover is not a “global crash handler,” it works only locally.
Here is an example of “self-defense” inside a goroutine:
package main
import (
"fmt"
"time"
)
func main() {
go func() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r) // recovered: boom
}
}()
panic("boom")
}()
time.Sleep(10 * time.Millisecond)
fmt.Println("program still alive") // program still alive
}
From an engineering-culture point of view, this looks like this: if you launch background work that can potentially panic (for example, due to a logic error, an unexpected nil, etc.), then either you are sure that a panic cannot happen, or you put a protective recover at the boundary of that background task. But turning recover into a “try/catch for every sneeze” is also not necessary: it worsens diagnostics and hides bugs.
7. Typical mistakes when launching goroutines
Mistake #1: expecting a “deterministic” execution order.
When you write two lines go f() and go g(), the brain really wants to read this as “first f, then g.” But concurrent code does not give such a contract: the scheduler can start g before f, can interleave their execution, or may not even have time to start one of them before the program ends. The reliable approach is to treat the order as undefined and not build correctness on it.
Mistake #2: believing that a goroutine will “keep the program alive.”
Beginners often think: “I launched a goroutine, so the program will wait until it finishes.” In Go that is false: if main ends, the process ends entirely, and all goroutines “disappear.” That is why bugs like “sometimes it prints, sometimes it doesn’t” appear. The cure here is not increasing Sleep, but using an explicit protocol for waiting for the background work to complete.
Mistake #3: trying to get a result from a goroutine via return.
It is very natural to want to “return a number from a background function.” But the go operator does not give you a variable where the return value can be stored. Therefore, the pattern “we launch computation in parallel and then take the result” requires other tools and discipline. At today’s step, it is useful to remember a simple rule: goroutines are good for background tasks and structuring work, but they do not automatically give you a “result in hand.”
Mistake #4: passing a pointer and expecting a stable value.
When you pass &x into a goroutine, you are sharing the address of a variable that other code may change. Because of that, the goroutine may see both the old value and the new one — depending on how the runtime schedules them. Sometimes that is exactly what you want, but more often for a beginner it is a source of mysterious “flaky” bugs. If you need a snapshot of the value at launch time, pass the value, not the pointer.
Mistake #5: a panic “in the background” without recover, which unexpectedly brings down the whole process.
A panic in a goroutine does not “fade away” by default and does not turn into an error somewhere in the logs — it ends the application when it reaches the top of that goroutine’s stack. If you launch background work and panics are possible there, think about the boundary of responsibility: either fix the cause of the panic, or place local defer + recover protection where it is justified.
GO TO FULL VERSION