第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

多個 goroutine 訪問/修改列表/地圖

多個 goroutine 訪問/修改列表/地圖

Go
猛跑小豬 2021-12-13 18:45:09
我正在嘗試使用 go lang 作為示例任務(wù)來實(shí)現(xiàn)一個多線程爬蟲來學(xué)習(xí)語言。它應(yīng)該掃描頁面,跟蹤鏈接并將它們保存到數(shù)據(jù)庫中。為了避免重復(fù),我嘗試使用 map 來保存我已經(jīng)保存的所有 URL。同步版本工作正常,但是當(dāng)我嘗試使用 goroutine 時遇到了麻煩。我正在嘗試將互斥鎖用作地圖的同步對象,并將通道用作協(xié)調(diào) goroutine 的一種方式。但顯然我對它們沒有清楚的了解。問題是我有很多重復(fù)的條目,所以我的地圖存儲/檢查無法正常工作。有人可以向我解釋如何正確執(zhí)行此操作嗎?
查看完整描述

1 回答

?
紫衣仙女

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個贊

好吧,您有兩個選擇,對于一些簡單的實(shí)現(xiàn),我建議將地圖上的操作分離到一個單獨(dú)的結(jié)構(gòu)中。


// Index is a shared page index

type Index struct {

    access sync.Mutex

    pages map[string]bool

}


// Mark reports that a site have been visited

func (i Index) Mark(name string) {

    i.access.Lock()

    i.pages[name] = true

    i.access.Unlock()

}


// Visited returns true if a site have been visited

func (i Index) Visited(name string) bool {

    i.access.Lock()

    defer i.access.Unlock()


    return i.pages[name]

}

然后,添加另一個結(jié)構(gòu),如下所示:


// Crawler is a web spider :D

type Crawler struct {

    index Index

    /* ... other important stuff like visited sites ... */

}


// Crawl looks for content

func (c *Crawler) Crawl(site string) {

    // Implement your logic here 

    // For example: 

    if !c.index.Visited(site) {

        c.index.Mark(site) // When marked

    }

}

這樣你就可以讓事情變得清晰明了,可能會多一點(diǎn)代碼,但絕對更具可讀性。您需要像這樣實(shí)例爬蟲:


sameIndex := Index{pages: make(map[string]bool)}

asManyAsYouWant := Crawler{sameIndex, 0} // They will share sameIndex

如果您想更深入地使用高級解決方案,那么我會推薦生產(chǎn)者/消費(fèi)者架構(gòu)。


查看完整回答
反對 回復(fù) 2021-12-13
  • 1 回答
  • 0 關(guān)注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號