Skip to content

Instantly share code, notes, and snippets.

@maksadbek
Created December 17, 2020 01:51
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 maksadbek/d83cae13c6402a62d40a4083d6e7fb24 to your computer and use it in GitHub Desktop.
Save maksadbek/d83cae13c6402a62d40a4083d6e7fb24 to your computer and use it in GitHub Desktop.
package main
import (
"time"
"fmt"
"context"
"sync"
)
func web() string {
time.Sleep(time.Millisecond * 100)
return "web"
}
func video() string {
time.Sleep(time.Millisecond * 1500)
return "video"
}
func music() string {
time.Sleep(time.Millisecond * 1000)
return "music"
}
func google() []string {
var result []string
ch := make(chan string)
scrapingDone := make(chan bool)
now := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
go func() {
for {
select {
case i, ok := <- ch:
if !ok {
fmt.Println("chan closed")
scrapingDone <- true
return
}
result = append(result, i)
case <-ctx.Done():
fmt.Println("done")
scrapingDone <- true
return
}
}
}()
go func() {
wg := sync.WaitGroup{}
wg.Add(3)
go func() {
ch <- web()
wg.Done()
}()
go func() {
ch <- video()
wg.Done()
}()
go func() {
ch <- music()
wg.Done()
}()
wg.Wait()
close(ch)
}()
<-scrapingDone
fmt.Println(time.Since(now))
return result
}
func main() {
fmt.Println(google())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment