Chapter 16: Concurrent Work

Introduksyon

Concurrency. Kung wa ka kabalo ana, maglisod jud kag sabot sa Go. Kanang goroutines (lightweight threads) ug channels (typed communication pipes) — mao nay nagpabilib nako sa Go sa una. Anhi nga chapter: goroutines, WaitGroups, mutexes, channels, select, ug context package. Lingaw ni, promise.

Goroutines

Ang goroutine kay murag mini na thread. Pero dili OS thread ha — gi-manage na sa Go runtime mismo, so barato ra kaayo. I-start gamit ang go keyword. Sige, tan-awa:

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

func main() {
    go say("world")
    say("hello")
}

Pero naay catch: pag-exit sa main, patay ang program. Sige, gusto ka mag-imagine ug goroutine. Wa kay makuha ana. Kung di ka maghulat, wa kay madawat. Gamit ug synchronization para maghulat jud.

Exercise 16.01: Using Concurrent Routines

Goal: I-launch ang duha ka goroutines na mag-print ug messages ug tan-awa ang interleaved output. Murag duha ka tao nagstorya sabay — magkagubot pero lingaw.

package main

import (
    "fmt"
    "time"
)

func printNums(prefix string) {
    for i := 1; i <= 5; i++ {
        fmt.Println(prefix, i)
        time.Sleep(50 * time.Millisecond)
    }
}

func main() {
    go printNums("A")
    go printNums("B")
    time.Sleep(500 * time.Millisecond)  // bati — gamit WaitGroup
}

WaitGroup

sync.WaitGroup kay murag taga-lista sa jeepney driver. Mag-add ka ug pasahero (Add), mag-ingon "naog ko" (Done), ug maghulat nga makababa ang tanan (Wait). Simple ra:

var wg sync.WaitGroup

for i := 1; i <= 3; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        fmt.Println("worker", id)
    }(i)
}
wg.Wait()
fmt.Println("all done")

Exercise 16.02: Experimenting with WaitGroup

Goal: I-launch ang 5 ka goroutines na mag-print ug ID ug gamit ug WaitGroup para maghulat bago mu-exit. Ayaw ug sige ug time.Sleep — wala ta sa party.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            fmt.Println("goroutine", id)
        }(i)
    }

    wg.Wait()
    fmt.Println("all goroutines complete")
}

Race Conditions

Ang race condition — murag duha ka tao nagsulat sa samang papel sabay. Magkagubot, magkabuang. Mahitabo ni kung daghang goroutines mu-access ug shared data na walay synchronization. Gamit ang -race flag para ma-detect:

// Race condition:
var counter int
for i := 0; i < 1000; i++ {
    go func() { counter++ }() // unsafe — daghang goroutines nagsulat sa counter
}

// Fix with mutex (see next section)
// go run -race main.go  // detects the race

Atomic Operations

Para simple counters ug flags, sync/atomic nagprovide ug lock-free operations. Murag self-checkout — walay nagbantay pero walay mangawat:

import "sync/atomic"

var counter int64

for i := 0; i < 1000; i++ {
    go func() { atomic.AddInt64(&counter, 1) }()
}

Pero kung complex imong shared state — ayawg atomic2 diha. Gamit ug sync.Mutex para sure.

Exercise 16.03: An Atomic Change

Goal: Gamit ug atomic.AddInt64 para safe i-increment ang counter gikan sa multiple goroutines. Walay mag-away, walay mag-lumpat.

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var counter int64
    var wg sync.WaitGroup

    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            atomic.AddInt64(&counter, 1)
        }()
    }

    wg.Wait()
    fmt.Println("counter:", counter)  // 100
}

Invisible Concurrency

Dili tanang concurrency problems obvious. Bisan simple patterns kay pwedeng mag-cause ug subtle bugs — murag ex nga nagpaka-okay ra pero broken diay. Gamit ang race detector (go run -race) regularly. Mas readable ang sync.Mutex kaysa atomic para complex logic. Kung maglibog ka, mutex lang sa:

type SafeCounter struct {
    mu sync.Mutex
    n  int
}

func (c *SafeCounter) Inc() {
    c.mu.Lock()
    c.n++
    c.mu.Unlock()
}

func (c *SafeCounter) Value() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.n
}

Activity 16.01: Listing Numbers

Goal: I-launch ang 10 ka goroutines na mu-add ug ID sa shared slice, protected by mutex. Ayaw papas-pas — i-lock sa dili pa mo-append.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var (
        mu   sync.Mutex
        nums []int
        wg   sync.WaitGroup
    )

    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            mu.Lock()
            nums = append(nums, id)
            mu.Unlock()
        }(i)
    }

    wg.Wait()
    fmt.Println(nums)
}

Channels

Ang channels kay typed conduits para communication between goroutines. Murag tubig-tubig: send gikan sa isa, receive sa pikas. Paghimo gamit make(chan T). Send gamit ch <- v, receive gamit v := <-ch:

ch := make(chan int)

// Sender goroutine
go func() {
    ch <- 42
}()

// Receiver
val := <-ch
fmt.Println(val)  // 42

Ang unbuffered channels mu-block until ready ang sender ug receiver. Synchronous — murag tagay, ikaw muhatag, ikaw mudawat. Ang buffered channels (make(chan T, N)) mu-block lang kung puno na ang buffer. Murag botelya — kung puno na, ayaw na pugsa.

Exercise 16.04: Exchange Greeting Messages via Channels

Goal: Magpadala ug greeting string through channel gikan sa goroutine paingon sa main. Simple communication — goroutine nagsulti, main naminaw.

package main

import "fmt"

func main() {
    ch := make(chan string)

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

    msg := <-ch
    fmt.Println(msg)
}

Exercise 16.05: Two-Way Message Exchange with Channels

Goal: Gamit ug duha ka channels para bidirectional communication between goroutines. Murag bola-bola — i-pass nimo, i-pass balik.

package main

import "fmt"

func main() {
    ping := make(chan string)
    pong := make(chan string)

    go func() {
        msg := <-ping
        pong <- msg + " pong"
    }()

    ping <- "ping"
    result := <-pong
    fmt.Println(result)
}

Exercise 16.06: Sum Numbers from Everywhere

Goal: I-split ang slice sa half, i-sum each half sa goroutine, ug i-combine ang results. Divide and conquer — pareha rag group project pero walay freeloader.

package main

import "fmt"

func sum(nums []int, ch chan int) {
    total := 0
    for _, n := range nums {
        total += n
    }
    ch <- total
}

func main() {
    nums := []int{1, 2, 3, 4, 5, 6}
    ch := make(chan int)

    go sum(nums[:3], ch)
    go sum(nums[3:], ch)

    a, b := <-ch, <-ch
    fmt.Println("total:", a+b)
}

Exercise 16.07: Request to Goroutines

Goal: Magpadala ug number sa goroutine, i-double ang value, ug ibalik. Murag sugo-sugo — "bai, i-double daw ni."

package main

import "fmt"

func main() {
    req := make(chan int)
    res := make(chan int)

    go func() {
        n := <-req
        res <- n * 2
    }()

    req <- 21
    result := <-res
    fmt.Println("doubled:", result)
}

The Importance of Concurrency

Ang concurrency nag-enable ug programs na mag-handle ug multiple tasks simultaneously — serving daghang HTTP requests, pag-process ug data in parallel, or pag-maintain ug responsiveness during long operations. Kung wala ni, magsige rag huwat ang imong app sama sa imong crush nga wala nag-reply. Ang Go goroutines nagamit ug gamay ra kaayo memory (a few KB each), pwede ka mag-launch ug thousands or even millions — dili pareha sa threads sa ubang language nga bug-at.

Exercise 16.08: Equally Splitting the Work between Routines

Goal: I-divide ang range sa numbers equally among N goroutines ug i-sum ang portion. Fair distribution — dili pareha sa group project na ikaw ray ga-work.

package main

import (
    "fmt"
    "sync"
)

func sumRange(start, end int, wg *sync.WaitGroup, results chan int) {
    defer wg.Done()
    total := 0
    for i := start; i <= end; i++ {
        total += i
    }
    results <- total
}

func main() {
    const n = 4
    var wg sync.WaitGroup
    results := make(chan int, n)

    chunkSize := 100 / n
    for i := 0; i < n; i++ {
        start := i*chunkSize + 1
        end := start + chunkSize - 1
        wg.Add(1)
        go sumRange(start, end, &wg, results)
    }

    wg.Wait()
    close(results)

    total := 0
    for r := range results {
        total += r
    }
    fmt.Println("total 1-100:", total)
}

Concurrency Patterns

Activity 16.02: Source Files

Goal: I-count ang lines sa multiple files concurrently gamit goroutines ug channels. Dili na mag-usausa — sabay-sabay para paspas.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func countLines(filename string, ch chan int) {
    f, err := os.Open(filename)
    if err != nil {
        ch <- 0
        return
    }
    defer f.Close()

    count := 0
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        count++
    }
    ch <- count
}

func main() {
    files := []string{"file1.txt", "file2.txt", "file3.txt"}
    ch := make(chan int)

    for _, f := range files {
        go countLines(f, ch)
    }

    total := 0
    for range files {
        total += <-ch
    }
    fmt.Println("total lines:", total)
}

Buffers

Ang buffered channels may capacity. Muramg botelya — kung puno na ang buffer, ang send mu-block hangtod may makuha. Ang receives mu-block lang kung walay sulod:

ch := make(chan int, 3)
ch <- 1  // doesn't block
ch <- 2  // doesn't block
ch <- 3  // doesn't block (buffer full)
// ch <- 4  // would block (buffer full)

fmt.Println(<-ch)  // 1
fmt.Println(<-ch)  // 2
fmt.Println(<-ch)  // 3

// Close to signal no more sends
close(ch)

// Range over channel
for v := range ch {
    fmt.Println(v)
}

Exercise 16.09: Notifying When Computation Has Finished

Goal: Gamit ug channel para mag-signal pag mahuman na ang long computation. Murag "done" na text sa imong miga — "naabot nako, sige na."

package main

import (
    "fmt"
    "time"
)

func compute(done chan bool) {
    fmt.Println("computing...")
    time.Sleep(1 * time.Second)
    fmt.Println("done")
    done <- true
}

func main() {
    done := make(chan bool)
    go compute(done)
    <-done  // wait for completion
    fmt.Println("main exiting")
}

Some More Common Practices

HTTP Servers

Ang Go HTTP server nag-handle sa each request sa iyahang goroutine automatically. Simple na concurrent request handling — walay thread pool nga i-manage, walay sakit sa ulo:

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
    // Each request runs in its own goroutine
}

Methods as Routines

Bisan unsa na function or method pwede i-run as goroutine. Gamit ug method values or closures. Basta naay func, pwd na nimo i-go:

type Worker struct{ ID int }

func (w Worker) Work() {
    fmt.Println("worker", w.ID, "working")
}

w := Worker{ID: 1}
go w.Work()  // method as goroutine

Exercise 16.10: A Structured Work

Goal: I-define ug struct naay method, i-launch multiple instances as goroutines, ug hulata ang tanan. Struct + method + goroutine = power combo:

package main

import (
    "fmt"
    "sync"
)

type Task struct {
    ID int
}

func (t Task) Run(wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("task", t.ID, "running")
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go Task{ID: i}.Run(&wg)
    }
    wg.Wait()
    fmt.Println("all tasks done")
}

Go Context Package

context.Context nagdala ug deadlines, cancellation signals, ug request-scoped values across API boundaries ug goroutines. Kung mag-request ka sa server, imong context murag ID card — nasulat didto kung kanus-a ma-expire, kinsa nag-request, ug pwede ba i-cancel:

ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()

select {
case result := <-doWork(ctx):
    fmt.Println(result)
case <-ctx.Done():
    fmt.Println("timeout:", ctx.Err())
}

func doWork(ctx context.Context) <-chan string {
    ch := make(chan string)
    go func() {
        select {
        case <-time.After(200 * time.Millisecond):
            ch <- "done"
        case <-ctx.Done():
            ch <- "cancelled"
        }
    }()
    return ch
}

Exercise 16.11: Managing Routines with Context

Goal: Gamit ug context.WithTimeout para i-cancel ang long-running goroutine after 50ms. Kung dugay kaayo, undangi nalang — ayaw pag-sige ug huwat:

package main

import (
    "context"
    "fmt"
    "time"
)

func slowOperation(ctx context.Context) string {
    select {
    case <-time.After(200 * time.Millisecond):
        return "completed"
    case <-ctx.Done():
        return "cancelled: " + ctx.Err().Error()
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    defer cancel()

    result := slowOperation(ctx)
    fmt.Println(result)
}

Summary