Back to Blog

Concurrent Programming with Goroutines - Go Tutorial for Beginners #24

Sandy LaneSandy Lane

Video: Concurrent Programming with Goroutines - Go Tutorial for Beginners #24 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Concurrent Programming with Goroutines in Go

Goroutines are Go's lightweight threads that enable concurrent execution of functions. By using the go keyword, you can start multiple functions simultaneously, improving efficiency and responsiveness in your programs. This example demonstrates launching goroutines, using anonymous functions, and synchronizing them with sync.WaitGroup.

Code

package main

import (
  "fmt"
  "sync"
  "time"
)

func main() {
  var wg sync.WaitGroup

  // Increment WaitGroup counter for 3 goroutines
  wg.Add(3)

  // Launch first goroutine
  go func() {
    defer wg.Done() // Signal completion
    fmt.Println("Goroutine 1 started")
    time.Sleep(1 * time.Second)
    fmt.Println("Goroutine 1 finished")
  }()

  // Launch second goroutine
  go func() {
    defer wg.Done()
    fmt.Println("Goroutine 2 started")
    time.Sleep(500 * time.Millisecond)
    fmt.Println("Goroutine 2 finished")
  }()

  // Launch third goroutine using a named function
  go worker(&wg)

  // Wait for all goroutines to finish
  wg.Wait()
  fmt.Println("All goroutines completed")
}

func worker(wg *sync.WaitGroup) {
  defer wg.Done()
  fmt.Println("Goroutine 3 started")
  time.Sleep(700 * time.Millisecond)
  fmt.Println("Goroutine 3 finished")
}

Key Points

  • The go keyword starts a new goroutine, allowing concurrent execution.
  • Anonymous functions can be launched as goroutines for concise concurrency.
  • sync.WaitGroup is essential for waiting until all goroutines complete.
  • Use wg.Add(n) to set the number of goroutines to wait for and wg.Done() to signal completion.
  • Goroutines are lightweight and managed by the Go runtime, enabling efficient multitasking.