Also what makes you think that ordering is mandated? Any of the goroutines can be scheduled to run. The odds of 1 running first seems intuitively higher but the should be nothing stopping the last to run first.
On Fri, Nov 11, 2016, 07:11 Henrik Johansson <dahankz...@gmail.com> wrote: > I think there is a race on the WaitGroup. Add all of them before the loop. > It might not matter for what you are seeing but anyway. > > What happens with an unbuffered channel? > > On Fri, Nov 11, 2016, 07:08 <mspauldin...@gmail.com> wrote: > > Hello, > > I've written a small program to demonstrate what I am seeing. If I use a > channel as a semaphore and set the size of the channel to 1, I would expect > that the executions of my handle function below would all be executed in > order, but it's not. For some reason the last item in the list is always > handled first, and then the remaining items are handled in order. Does > anyone know why I see this behavior? > > Program: > > package main > > import ( > "fmt" > "sync" > "time" > ) > > var wg sync.WaitGroup > var sem chan int > > func handle(i int) { > defer wg.Done() > fmt.Println("waiting: ", i) > sem <- 1 > fmt.Println("processing: ", i) > time.Sleep(1 * time.Second) > <-sem > } > > func main() { > sem = make(chan int, 1) > nums := []int{1, 2, 3, 4} > > for _, i := range nums { > wg.Add(1) > go handle(i) > } > wg.Wait() > } > > Output: > > waiting: 4 > processing: 4 > waiting: 1 > waiting: 2 > waiting: 3 > processing: 1 > processing: 2 > processing: 3 > > > > -- > 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+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > > -- 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+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.