Last active
June 26, 2023 09:33
-
-
Save oNddleo/c3a9b0a4fbd453373ca9b3d9608c8f09 to your computer and use it in GitHub Desktop.
Load Balancing Channel Example
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" | |
) | |
func publisher() <-chan int { | |
c := make(chan int) | |
go func() { | |
for i := 1; i <= 1000; i++ { | |
c <- i | |
} | |
close(c) | |
}() | |
return c | |
} | |
func consumer(c <-chan int, name string, wg *sync.WaitGroup) { | |
counter := 0 | |
for value := range c { | |
fmt.Printf("Consumer %s is doing task %d\n", name, value) | |
counter++ | |
} | |
fmt.Printf("Consumer %s has finished %d task(s)\n", name, counter) | |
wg.Done() | |
} | |
func main() { | |
myChan := publisher() | |
maxConsumer := 5 | |
var wg sync.WaitGroup | |
wg.Add(maxConsumer) | |
for i := 1; i <= maxConsumer; i++ { | |
go consumer(myChan, fmt.Sprintf("%d", i), &wg) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment