Okay, that makes sense. I've updated my solution so that in the case that the channel only has a capacity of 1 the processing will be done without goroutines to ensure that it is done in serial. In the case that the channel capacity is larger then I don't care about how processing is ordered.
Is this is a good solution below, or is there a better way to handle this? https://play.golang.org/p/J2bi4PJJFd On Thursday, November 10, 2016 at 10:18:16 PM UTC-8, Dave Cheney wrote: > > The runtime does not give any guarentee when you use a go statement if the > goroutine being spawned will run immediately, or if control will remain > with the original goroutine. > > This program, https://play.golang.org/p/-OcCzgt4Jy, which pauses all > goroutines while they are being created exhibits the same behaviour as you > see and may explain what you are seeing. > > On Friday, 11 November 2016 17:08:39 UTC+11, mspaul...@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.