Imagine you're cooking rice 🍚 and boiling water ☕ at the same time.
That's concurrency — doing multiple things at once!
Go makes this super easy using something called goroutines.
Let’s explore 👇
A goroutine is like a mini worker that runs in the background.
You create one by adding just one word:
go sayHello()Now sayHello() runs at the same time as the rest of your code.
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine!")
}
func main() {
go sayHello() // runs in background
time.Sleep(1 * time.Second) // give it time!
fmt.Println("Main is done.")
}📝 If you remove time.Sleep, you might not see the goroutine’s message!
That's because Go exits as soon as main() finishes.
You can use goroutines to:
Download files while showing UI
Handle 1000 users at once
Do heavy math while staying responsive
All with the go keyword!
Goroutines can talk to each other using channels:
ch := make(chan string)
go func() {
ch <- "Hello!"
}()
msg := <-ch
fmt.Println(msg)🧠 ch <- "Hello!" sends
📥 <-ch receives
Let’s add a buffer (space for values):
ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch)
fmt.Println(<-ch)This is like a pipe that can hold 2 items before blocking.
select {
case msg := <-ch1:
fmt.Println("Got", msg)
case msg := <-ch2:
fmt.Println("Got", msg)
}Go will pick whichever is ready first!
Goroutines don’t run in order
They might finish quickly or slowly
Use
sync.WaitGroupor channels to coordinateDon't forget to give time for goroutines to finish!
gomakes a function run in the backgroundChannels help goroutines talk to each other
Concurrency is built-in in Go and very easy to use
You can do many things at once — with few lines of code
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.