Last active
April 24, 2019 19:07
-
-
Save mish15/97aec168962192718150da29ce672d72 to your computer and use it in GitHub Desktop.
No blocking channel based queue processor example
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 ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
queue := make(chan int, 5) // buffer up to 5 items to be processed | |
done := make(chan bool) | |
go func() { | |
for n := range queue { | |
time.Sleep(100 * time.Millisecond) // fake longer processing time | |
fmt.Println(n) | |
} | |
fmt.Println("done processing") | |
close(done) | |
}() | |
for i := 0 ; i < 10; i++ { | |
queue <- i // add items to be processed | |
} | |
fmt.Println("done queuing...") | |
close(queue) // because this is closed, the range loop above will exit | |
<- done // block until the queue is fully processed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment