Skip to content

Instantly share code, notes, and snippets.

@Oxygenesis
Created January 11, 2024 14:02
Show Gist options
  • Save Oxygenesis/4aa569ee102615544f928d52632c0e47 to your computer and use it in GitHub Desktop.
Save Oxygenesis/4aa569ee102615544f928d52632c0e47 to your computer and use it in GitHub Desktop.
Fan in Fan out pattern golang, managing concurrency
package main
import (
"fmt"
"sync"
)
// worker used to process data
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "processing job", j)
results <- j * 2 // Sample processing
}
}
func main() {
const numJobs = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
// Fan-Out: Starting 3 workers
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// Sending jobs to the workers
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
// Fan-In: Collecting results
for a := 1; a <= numJobs; a++ {
<-results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment