Explanation of Channels from 'Tour of Go' Webcrawler Exercise -


i'm going through 'a tour of go' , have been editing of lessons make sure understand them. have question regarding answer provided following exercise: https://tour.golang.org/concurrency/10 can found here: https://github.com/golang/tour/blob/master/solutions/webcrawler.go

i have question regarding following section:

done := make(chan bool) i, u := range urls {     fmt.printf("-> crawling child %v/%v of %v : %v.\n", i, len(urls), url, u)     go func(url string) {         crawl(url, depth-1, fetcher)         done <- true     }(u) } i, u := range urls {     fmt.printf("<- [%v] %v/%v waiting child %v.\n", url, i, len(urls), u)     <-done } fmt.printf("<- done %v\n", url) 

what purpose adding , removing true the channel done , running 2 separate loops have? block until go routine finishes? know example exercise, doesn't kind of defeat point of spinning out new thread in first place?

why can't call go crawl(url, depth-1, fetcher) without 2nd loop , done channel? because of shared memory space variables?

thanks!

the first for loop schedules multiple goroutines run , iterating on slice of urls.

the second loop blocks on each url, waiting until corresponding crawl() invocation has completed. crawl()ers run , work in parallel , block exiting until main thread has chance receive message on done channel each url.

in opinion, better way implement use sync.waitgroup. code log wrong thing depending on how long each crawl() invocation takes unless fetcher locks.

if want sure of url finished crawl()ing, change type of done channel string , send url instead of true upon crawl() completion. then, receive url in second loop.

example:

done := make(chan string) _, u := range urls {     fmt.printf("-> crawling %s\n", u)     go func(url string) {         crawl(url, depth-1, fetcher)         done <- url     }(u) } range urls {     fmt.printf("<- waiting next child\n")     u := <-done     fmt.printf("  done... %s\n", u) } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -