Created
March 18, 2014 08:58
-
-
Save youpy/9616200 to your computer and use it in GitHub Desktop.
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 ( | |
"errors" | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
rand.Seed(time.Now().UTC().UnixNano()) | |
items := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} | |
maxProcs := 5 | |
queue := make(chan int, maxProcs) | |
reply := make(chan error) | |
for i := 0; i < maxProcs; i++ { | |
go work(queue, reply) | |
} | |
go broker(items, queue) | |
for i := 0; i < len(items); i++ { | |
err := <-reply | |
if err != nil { | |
fmt.Printf("error: %v\n", err) | |
} | |
} | |
return | |
} | |
func broker(items []int, queue chan<- int) { | |
for _, item := range items { | |
queue <- item | |
} | |
close(queue) | |
} | |
func work(queue <-chan int, reply chan<- error) { | |
for { | |
var err error | |
item, ok := <-queue | |
if !ok { | |
return | |
} | |
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) | |
if item != 5 { | |
fmt.Println(item) | |
} else { | |
err = errors.New("value is 5") | |
} | |
reply <- err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment