Skip to content

Pipelines

Johnny Boursiquot edited this page May 31, 2024 · 1 revision

Pipelines are a series of stages connected by channels where each stage is a goroutine that performs some processing on the data and passes it to the next stage. This pattern is useful for structuring programs that handle streams of data, allowing for concurrent processing and easy composition of different stages.

Key Concepts

  1. Stages: Each stage is a function that takes an input channel and an output channel.
  2. Channels: Channels connect stages, passing data from one to the next.
  3. Goroutines: Each stage runs in its own goroutine, allowing for concurrent execution.

Example

package main

import (
    "fmt"
    "sync"
)

// Stage 1: Generate numbers
func generate(nums ...int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    return out
}

// Stage 2: Square numbers
func square(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for n := range in {
            out <- n * n
        }
        close(out)
    }()
    return out
}

// Stage 3: Print results
func printResults(in <-chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    for n := range in {
        fmt.Println(n)
    }
}

func main() {
    nums := generate(1, 2, 3, 4, 5)
    squares := square(nums)

    var wg sync.WaitGroup
    wg.Add(1)
    go printResults(squares, &wg)

    wg.Wait()
}

Discussion

  1. Do you need a waitgroup for printResults in the above example?
  2. Make one change to cause the program to deadlock. Why did that work?

Exercise 5: Pipelines

Time to leverage another pattern in our port scanner. You'll need to create a pipeline with multiple steps (feed ports in, do the scan, gather the results). Head on over.

Clone this wiki locally