Skip to content

Instantly share code, notes, and snippets.

@BirkhoffLee
Created January 19, 2021 17:14
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 BirkhoffLee/d09c920620d2dadae0e09dab67309f61 to your computer and use it in GitHub Desktop.
Save BirkhoffLee/d09c920620d2dadae0e09dab67309f61 to your computer and use it in GitHub Desktop.
My first concurrent program with goroutine (for commemoration purposes)
// https://tour.golang.org/concurrency/10
package main
import (
"fmt"
"sync"
)
type SafeMap struct {
mu sync.Mutex
v []string
}
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
}
func contains(search string, s []string) bool {
for _, a := range s {
if a == search {
return true
}
}
return false
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func (c *SafeMap) Crawl(url string, depth int, fetcher Fetcher, wg *sync.WaitGroup) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
defer wg.Done()
//fmt.Printf("crawling: %s\n", url)
if depth <= 0 {
return
}
c.mu.Lock()
if contains(url, c.v) {
c.mu.Unlock()
return
}
c.v = append(c.v, url)
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
c.mu.Unlock()
return
}
c.mu.Unlock()
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
//fmt.Printf("firing next: %s\n", u)
wg.Add(1)
go c.Crawl(u, depth-1, fetcher, wg)
}
return
}
func main() {
c := SafeMap{v: make([]string, 100)}
var wg sync.WaitGroup
wg.Add(1)
go c.Crawl("https://golang.org/", 4, fetcher, &wg)
wg.Wait()
fmt.Printf("Complete")
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment