Skip to content

Instantly share code, notes, and snippets.

@kylewolfe
Last active December 27, 2020 17:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylewolfe/7c54018a9ed16517c0dd to your computer and use it in GitHub Desktop.
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
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