Skip to content

Instantly share code, notes, and snippets.

@yasuoza
Created July 29, 2020 02:09
Show Gist options
  • Save yasuoza/dd4388a3f55250a6a3efcbfd944e9750 to your computer and use it in GitHub Desktop.
Save yasuoza/dd4388a3f55250a6a3efcbfd944e9750 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
fmt.Println(time.Now())
n := 10
ch := make(chan int, n)
wg := &sync.WaitGroup{}
wg.Add(cap(ch))
for i := 0; i < n; i++ {
go func(i int) {
defer wg.Done()
if execute(i) {
fmt.Println("sending :", i)
ch <- i
}
}(i)
}
go func(wg *sync.WaitGroup) {
wg.Wait()
close(ch)
}(wg)
for i := range ch {
fmt.Println("received: ", i)
}
fmt.Println(time.Now())
}
func execute(i int) bool {
time.Sleep(1 * time.Second)
return i%2 == 0
}
2020-01-29 11:08:32.194148 +0900 JST m=+0.000080461
sending : 2
received: 2
sending : 8
sending : 4
received: 8
received: 4
sending : 0
received: 0
sending : 6
received: 6
2020-01-29 11:08:33.194603 +0900 JST m=+1.000513577
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment