Repository navigation
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.
- Stages: Each stage is a function that takes an input channel and an output channel.
- Channels: Channels connect stages, passing data from one to the next.
- Goroutines: Each stage runs in its own goroutine, allowing for concurrent execution.
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()
}- Do you need a waitgroup for
printResultsin the above example? - Make one change to cause the program to deadlock. Why did that work?
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.