Skip to content

Instantly share code, notes, and snippets.

@poundifdef
Created March 28, 2024 19:02
Show Gist options
  • Save poundifdef/3cb42cd8d23a3b92bb9092d04f3f6f9c to your computer and use it in GitHub Desktop.
Save poundifdef/3cb42cd8d23a3b92bb9092d04f3f6f9c to your computer and use it in GitHub Desktop.
Only produce when a consumer is ready
package main
import (
"fmt"
"sync"
"time"
)
func Produce(values chan<- int, ready <-chan bool) {
for {
<-ready
fmt.Println("Produced a value!")
values <- 42
}
}
func Consume(values <-chan int, ready chan<- bool) {
ready <- true
for v := range values {
fmt.Println(v)
time.Sleep(5 * time.Second)
ready <- true
}
}
func main() {
values := make(chan int)
ready := make(chan bool)
var wg sync.WaitGroup
wg.Add(1)
go Produce(values, ready)
go Consume(values, ready)
go Consume(values, ready)
go Consume(values, ready)
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment