Skip to content

Instantly share code, notes, and snippets.

@porjo
Last active December 23, 2015 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save porjo/6648966 to your computer and use it in GitHub Desktop.
Save porjo/6648966 to your computer and use it in GitHub Desktop.
Launch tasks and wait for finish
//
// Example thanks to DMorsing on #go-nuts Freenode channel
// http://play.golang.org/p/dmUfGKnbZ3
//
package main
import "fmt"
import "time"
import "math/rand"
import "sync"
var wg sync.WaitGroup
func task(ch chan bool, cancel chan struct{}) {
defer wg.Done()
for i := 0; i < rand.Int()%10+1; i++ {
time.Sleep(1 * time.Second)
// some result that was probably way expensive to calculate
result := true
select {
case ch <- result:
case <-cancel:
}
}
}
func main() {
resultch := make(chan bool)
cancelch := make(chan struct{})
fmt.Println("Launching tasks")
wg.Add(3)
go task(resultch, cancelch)
go task(resultch, cancelch)
go task(resultch, cancelch)
i := <-resultch
fmt.Println("got result, it was", i)
close(cancelch)
fmt.Println("Quitting main...")
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment