RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 17: Go Concurrency – Doing Many Things at Once, Easily! 🧠⚡

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

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.WaitGroup or channels to coordinate

  • Don't forget to give time for goroutines to finish!

  • go makes a function run in the background

  • Channels 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

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.