Created
January 11, 2024 14:02
-
-
Save Oxygenesis/4aa569ee102615544f928d52632c0e47 to your computer and use it in GitHub Desktop.
Fan in Fan out pattern golang, managing concurrency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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