Search code examples
goconcurrencyproducer-consumergoroutine

How do I add an object to a channel from a goroutine that is receiving data from that channel?


Basically, I am trying to write a concurrent sitemap crawler using goroutines. One sitemap can contain links to multiple sitemaps which can contain links to other sitemaps etc.

Right now, this is my design:

worker:
     - receives url from channel
     - processesUrl(url)
processUrl:
     for each link in lookup(url):
         - if link is sitemap:
                channel <- url
           else:
               print(url)
main:
    - create 10 workers
    - chanel <- root url

the problem is that the worker won't accept a new url from the channel until processUrl() is finished and processUrl won't finish until a worker accepts a new url from the channel if it is adding a url to the channel. What concurrent design can I use to add the url to a task queue without a channel and without busy-waiting or without waiting for channel <- url?

Here is the actual code if it helps:

func (c *SitemapCrawler) worker() {
    for {
        select {
        case url := <-urlChan:
            fmt.Println(url)
            c.crawlSitemap(url)
        }
    }
}
func crawlUrl(url string) {
    defer crawlWg.Done()
    crawler := NewCrawler(url)
    for i := 0; i < MaxCrawlRate*20; i++ {
        go crawler.worker()
    }
    crawler.getSitemaps()
    pretty.Println(crawler.sitemaps)
    crawler.crawlSitemaps()
}
func (c SitemapCrawler) crawlSitemap(url string) {
    c.limiter.Take()
    resp, err := MakeRequest(url)
    if err != nil || resp.StatusCode != 200 {
        crawlWg.Done()
        return
    }
    var resp_txt []byte
    if strings.Contains(resp.Header.Get("Content-Type"), "html") {
        crawlWg.Done()
        return
    } else if strings.Contains(url, ".gz") || resp.Header.Get("Content-Encoding") == "gzip" {
        reader, err := gzip.NewReader(resp.Body)
        if err != nil {
            crawlWg.Done()
            panic(err)
        } else {
            resp_txt, err = ioutil.ReadAll(reader)
            if err != nil {
                crawlWg.Done()
                panic(err)
            }
        }
        reader.Close()
    } else {
        resp_txt, err = ioutil.ReadAll(resp.Body)
        if err != nil {
            //panic(err)
            crawlWg.Done()
            return
        }
    }
    io.Copy(ioutil.Discard, resp.Body)
    resp.Body.Close()

    d, err := libxml2.ParseString(string(resp_txt))
    if err != nil {
        crawlWg.Done()
        return
    }
    results, err := d.Find("//*[contains(local-name(), 'loc')]")
    if err != nil {
        crawlWg.Done()
        return
    }
    locs := results.NodeList()
    printLock.Lock()
    for i := 0; i < len(locs); i++ {
        newUrl := locs[i].TextContent()
        if strings.Contains(newUrl, ".xml") {
            crawlWg.Add(1)
            //go c.crawlSitemap(newUrl)
            urlChan <- newUrl
        } else {
            fmt.Println(newUrl)
        }
    }
    printLock.Unlock()

    crawlWg.Done()
}

Solution

  • Write operations to channels are blocking when the channel is not buffered.

    To create a buffered channel:

    urlChan := make(chan string, len(allUrls))
    

    When this channel is full however, write operations will block again.

    Alternatively you could use a switch. When the write 'fails' it will immediately fall through to default

    select {
    case urlChan <- url:
        fmt.Println("received message")
    default:
        fmt.Println("no activity")
    }
    

    To have a timeout on writing to the channel do the following

    select {
    case urlChan <- url:
        fmt.Println("received message")
    case <-time.After(5 * time.Second):
        fmt.Println("timed out")
    }
    

    Or finally put the write event in a separate go channel

    func write() {
        urlChan <- url
    }
    
    go write()