Skip to content

Instantly share code, notes, and snippets.

@glesica glesica/pool.go
Created Jan 27, 2015

Embed
What would you like to do?
Simple example of a goroutine pool.
package main
import (
"fmt"
"sync"
)
func main() {
numbers := make(chan int, 10)
squares := make(chan int, 10)
squareGroup := new(sync.WaitGroup)
printGroup := new(sync.WaitGroup)
// Create 1 worker to print the squares
printGroup.Add(1)
go func() {
for square := range squares {
fmt.Println(square)
}
printGroup.Done()
}()
// Create 4 workers to square numbers
for i := 0; i < 4; i++ {
squareGroup.Add(1)
go func() {
for number := range numbers {
squares <- (number * number)
}
squareGroup.Done()
}()
}
// Square some numbers!
for i := 0; i < 10; i++ {
numbers <- i
}
// Wait for all the numbers to be squared
close(numbers)
squareGroup.Wait()
// Wait for all the squares to be printed
close(squares)
printGroup.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.