Created
December 1, 2022 19:01
-
-
Save nikooo777/0e146b22b54b3655680bf3266cdf0de1 to your computer and use it in GitHub Desktop.
Producer/Consumers in Go with generics (untested)
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 ( | |
"sync" | |
log "github.com/sirupsen/logrus" | |
) | |
func produce[T any](resources []T, jobs chan<- T, wg *sync.WaitGroup) { | |
defer wg.Done() | |
for _, msg := range resources { | |
jobs <- msg | |
} | |
} | |
func consume[T any](worker int, jobs <-chan T, wg *sync.WaitGroup) { | |
defer wg.Done() | |
for msg := range jobs { | |
log.Infof("product %v is consumed by worker %v", msg, worker) | |
} | |
} | |
const consumerCount int = 3 | |
func main() { | |
jobs := make(chan int, 10) | |
producerWg := sync.WaitGroup{} | |
consumerWg := sync.WaitGroup{} | |
producerWg.Add(1) | |
go produce([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, jobs, &producerWg) | |
for i := 0; i < consumerCount; i++ { | |
consumerWg.Add(1) | |
go consume(i, jobs, &consumerWg) | |
} | |
producerWg.Wait() | |
close(jobs) | |
consumerWg.Wait() | |
log.Infof("All products are consumed.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment