use channel to limit go routines

tags: learning go programming

content

  • channel is a way for the go routines to talk to each other
  • channel has a blocking mechanism
    • when the channel buffer is full, go routines that write to the channel will be blocked
limit := make(chan bool, 8)  // this channel could be any type
for event := range someEvent.Stream {
	// NOTE: occupy a slot in the channel
	limit <- true
	go func(e eventType) {
		processEvent(e)
		// NOTE: release the slot after processing is done:
		<-limit
	}(event)
}
  • the above code limits the number of go routine to be 8

up

down

reference