Skip to content

Instantly share code, notes, and snippets.

@maksadbek
Created Dec 17, 2020
Embed
What would you like to do?
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