Created
December 17, 2020 01:51
-
-
Save maksadbek/d83cae13c6402a62d40a4083d6e7fb24 to your computer and use it in GitHub Desktop.
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 ( | |
"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