Created
September 10, 2011 17:37
-
-
Save kylelemons/1208554 to your computer and use it in GitHub Desktop.
Using "close" to stop multiple goroutines
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
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
wg := new(sync.WaitGroup) | |
stop := make(chan bool) | |
data := make(chan int) | |
for i := 0; i < 10; i++ { | |
wg.Add(1) | |
go func(id int) { | |
defer wg.Done() | |
for { | |
select { | |
case <-stop: | |
return | |
case data <- id: | |
} | |
} | |
}(i) | |
} | |
for i := 0; i < 50; i++ { | |
fmt.Println(<-data) | |
} | |
close(stop) | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment