Created
October 23, 2020 07:07
-
-
Save TheNilesh/8fd9355ed48df079dc942286424a11c4 to your computer and use it in GitHub Desktop.
Limit number of goroutines reading from 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" | |
"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