Section 6 of 12

Goroutines & Channels

Master concurrent programming with goroutines and channels

Course Progress

Section 6 of 12

50% complete

Tutorials

Goroutines

Goroutines are lightweight threads managed by the Go runtime. They make concurrent programming simple and efficient.

Code Examples

Basic Goroutinesgo
package main

import (
    "fmt"
    "time"
)

func say(msg string) {
    for i := 0; i < 3; i++ {
        fmt.Println(msg, i)
        time.Sleep(100 * time.Millisecond)
    }
}

func main() {
    // Run sequentially
    // say("Hello")
    // say("World")
    
    // Run concurrently with goroutines
    go say("Hello")
    go say("World")
    
    // Give goroutines time to finish
    time.Sleep(1 * time.Second)
}

Channels

Channels allow goroutines to communicate safely. They're the backbone of Go's concurrency model.

Code Examples

Channel Basicsgo
package main

import (
    "fmt"
)

func main() {
    // Create a channel
    results := make(chan string)
    
    // Send to channel in goroutine
    go func() {
        results <- "Hello from goroutine"
    }()
    
    // Receive from channel
    msg := <-results
    fmt.Println(msg)
    
    // Buffered channel
    messages := make(chan string, 2)
    messages <- "first"
    messages <- "second"
    
    fmt.Println(<-messages)
    fmt.Println(<-messages)
}
Channel Patternsgo
package main

import (
    "fmt"
)

func main() {
    // Range over channel
    numbers := make(chan int)
    
    go func() {
        for i := 1; i <= 3; i++ {
            numbers <- i
        }
        close(numbers)
    }()
    
    for num := range numbers {
        fmt.Println(num)
    }
    
    // Select statement
    ch1 := make(chan string)
    ch2 := make(chan string)
    
    go func() { ch1 <- "result 1" }()
    go func() { ch2 <- "result 2" }()
    
    for i := 0; i < 2; i++ {
        select {
        case res := <-ch1:
            fmt.Println(res)
        case res := <-ch2:
            fmt.Println(res)
        }
    }
}

Exercises

Sum Numbers Concurrently

Use goroutines to sum arrays concurrently

ADVANCED

Starter Code:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    
    // TODO: Split array and sum concurrently using goroutines and channels
}

Hands-on Project

Web Scraper with Rate Limiting

Build a concurrent web scraper with goroutines and channels

ADVANCED

Learning Objectives

  • >Use goroutines for concurrency
  • >Manage channels
  • >Implement rate limiting

Project Tips

  • > Start by understanding the requirements
  • > Break the project into smaller tasks
  • > Test your code frequently as you build
  • > Add error handling throughout your code
  • > Consider edge cases and validate inputs
  • > Document your code with comments