Last active
December 23, 2015 14:29
-
-
Save porjo/6648966 to your computer and use it in GitHub Desktop.
Launch tasks and wait for finish
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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