Skip to content

Instantly share code, notes, and snippets.

@TheNilesh
Created October 23, 2020 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheNilesh/8fd9355ed48df079dc942286424a11c4 to your computer and use it in GitHub Desktop.
Save TheNilesh/8fd9355ed48df079dc942286424a11c4 to your computer and use it in GitHub Desktop.
Limit number of goroutines reading from channel
package main
import (
"fmt"
"os"
"os/signal"
"sync"
)
var wg sync.WaitGroup
var osInterrupt bool
const maxThreads = 5 // Number of maximum goroutines
func main() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
q := make(chan string)
wg.Add(1)
go produce(q)
for i := 0; i < maxThreads; i++ {
wg.Add(1)
go consume(q)
}
go func() {
<-c
fmt.Println("Interrupt recvd")
osInterrupt = true
}()
wg.Wait()
fmt.Println("Graceful exit")
}
func produce(q chan string) {
fmt.Println("Production started")
i := 0
for {
if osInterrupt { //TODO: Is this thread-safe
close(q)
break
}
q <- fmt.Sprintf("%d", i)
i++
}
fmt.Println("Production stopped")
wg.Done()
}
func consume(q chan string) {
fmt.Println("Consumption started")
for {
a, ok := <-q
if !ok { // channel has been closed
wg.Done()
fmt.Println("Consumption stopped")
return
}
fmt.Println(a)
// time.Sleep(2 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment