Back to Blog
Concurrency in Go

4/12/20244 min read

Concurrency in Go

Go was designed with concurrency in mind, providing goroutines and channels as first-class citizens. These primitives make it easy to write concurrent programs that are both efficient and easy to reason about.

⚠️ Concurrency is powerful but hard to get right — race conditions and deadlocks can ruin your day!

Creating Goroutines

go
func myFunction() {
    fmt.Println("Running in goroutine")
}

func main() {
    go myFunction() // Start as goroutine
    time.Sleep(time.Second) // Wait for goroutine
}

Using Anonymous Functions

go
go func() {
    fmt.Println("Anonymous goroutine")
}()

Channels

Channels are Go's way of communicating between goroutines safely.

go
ch := make(chan string)

go func() {
    ch <- "Hello from goroutine"
}()

message := <-ch
fmt.Println(message)

Synchronization with Mutex

go
import "sync"

var (
    count int
    mu    sync.Mutex
)

func increment() {
    mu.Lock()
    defer mu.Unlock()
    count++
}

WaitGroups and Worker Pools

go
import "sync"

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            doWork(id)
        }(i)
    }

    wg.Wait() // Wait for all goroutines
}

Buffered Channels for Worker Pools

go
jobs := make(chan int, 100)
results := make(chan int, 100)

// Start workers
for w := 0; w < 3; w++ {
    go worker(jobs, results)
}

// Send jobs
for j := 0; j < 5; j++ {
    jobs <- j
}
close(jobs)

Common Pitfalls

  • Race Conditions (use go run -race to detect)
  • Deadlocks (circular channel dependencies)
  • Goroutine Leaks (goroutines that never exit)

❗ Always consider using channels or sync primitives when sharing data between goroutines.

Summary

Go's concurrency model built on goroutines and channels makes it easy to write concurrent code that's both efficient and maintainable. Master these primitives to build scalable, high-performance applications.

🔍 "Don't communicate by sharing memory; share memory by communicating." – Go Proverb

Other posts that might interest you...