Ok, I think I got it, but now I need to understand how to avoid a deadlock (all routines are asleep)
package main
import (
"fmt"
"time"
"math/rand"
"sync"
)
var w sync.WaitGroup
func pupulateChan(c chan int) {
for i := 0; i < 100; i++ {
c <- i
}
}
func worker(i int, c chan int) {
for{
val, open := <-c
if(open == false) {
break
}
fmt.Println("worker", i, "recieved", val)
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))
}
w.Done()
}
func main() {
//define worker count
workers := 10
//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()
}--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
How would I go this as I can see a lot of my future projects doing this. Say I have one go routine (or main function) reading from a result set or text file, how would I evenly startup x number of go routines and evenly distribute the workload across them? So in other words, unless theres not enough work to go around, there should always be x go routines (no more) executing what my main function is feeding out.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.