Created
July 15, 2020 20:05
-
-
Save ddadlani/5eeb4e90f6a19dad1d1ecea1742befae to your computer and use it in GitHub Desktop.
Example for multiple producers and consumers for a channel
This file contains hidden or 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 main() { | |
eventBus := make(chan string) | |
wg := &sync.WaitGroup{} | |
wg.Add(20) | |
go eventProducers(eventBus, wg) | |
for i := 1; i <= 15; i++ { | |
go func(eventBus chan string, id int, wg *sync.WaitGroup) { | |
select { | |
case msg := <-eventBus: | |
fmt.Printf("id: %v, event: %v\n", id, msg) | |
} | |
wg.Done() | |
}(eventBus, i, wg) | |
} | |
wg.Wait() | |
close(eventBus) | |
fmt.Println("exiting") | |
} | |
func eventProducers(eventBus chan string, wg *sync.WaitGroup) { | |
for i := 1; i <= 5; i++ { | |
go func(wg *sync.WaitGroup, eventBus chan string, id int) { | |
for j := 1; j <= 3; j++ { | |
eventBus <- fmt.Sprintf("%v.%v", id, j) | |
} | |
wg.Done() | |
}(wg, eventBus, i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment