-
-
Save kylewolfe/7c54018a9ed16517c0dd to your computer and use it in GitHub Desktop.
A simple example of how to evenly spread work amoung n go routines
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" | |
"sync" | |
"time" | |
"math/rand" | |
) | |
var w sync.WaitGroup | |
func pupulateChan(c chan int) { | |
for i := 0; i < 10; i++ { | |
c <- i | |
} | |
close(c) | |
} | |
func worker(i int, c chan int) { | |
for val := range c { | |
rand := rand.New(rand.NewSource(time.Now().UnixNano())) | |
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond) //act like we're doing something | |
fmt.Println("worker", i, "recieved", val) | |
} | |
fmt.Println("worker", i, "done") | |
w.Done() | |
} | |
func main() { | |
//define worker count | |
workers := 2 | |
//create channel | |
c := make(chan int) | |
//populate the channel | |
go pupulateChan(c) | |
//tell sync how many goroutines are out there | |
w.Add(workers) | |
//start workers to read from channel | |
for i := 0; i < workers; i++ { | |
go worker(i, c) | |
} | |
//wait for goroutines to complete | |
w.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment