原料藥 : https://jsonmock.hackerrank.com/api/articles?page=1package mainimport ( "fmt" "net/http" "encoding/json" "strconv" "sync")type ArticleResponse struct { Page int `json:"page"` PerPage int `json:"per_page"` Total int `json:"total"` TotalPages int `json:"total_pages"` Data []Article `json:"data"`}type Article struct { Title string `json:"title"` URL string `json:"url"` Author string `json:"author"` NumComments int `json:"num_comments"` StoryID int32 `json:"story_id"` StoryTitle string `json:"story_title"` StoryURL string `json:"story_url"` ParentID int32 `json:"parent_id"` CreatedAt int `json:"created_at"`}type CommentTitle struct{ NumberOfComments int `json:"number_of_comments"` Title string `json:"title"` Page int `json:"from_page"`}const ( GET_HOST_URL = "https://jsonmock.hackerrank.com/" PATH = "api/articles")var wg sync.WaitGroupfunc main(){ comment_title_chan := make(chan CommentTitle) var commentTitleSlice []CommentTitle // pilot call to get total number of pages totalPage := makePaginatedRequest(1, comment_title_chan, true) // making concurrent requests to multiple pages at once for j:=1;j<=totalPage;j++{ go makePaginatedRequest(j, comment_title_chan, false) }}問題陳述:有一個 api 在查詢參數中傳遞頁碼時提供數據。我需要調用所有頁面并獲取具有有效標題和評論數量字段的所有文章。溶液:步驟1:我首先對api進行試點調用以了解頁面數,因為它是響應json的一部分。第2步:我啟動多個goroutines(goroutines的數量=總頁數)第3步:每個goroutine將調用相應的頁面并獲取數據并將其發(fā)送到數據通道。步驟4:將通道中接收到的數據追加到切片上,切片用于進一步計算(根據文章的評論數量進行排序)問題:我不知道記錄總數 - 有多少是有效的,因此我不知道何時關閉來自發(fā)送方的通道(在我的場景中有多個發(fā)送方和單個接收方)。我嘗試再使用一個額外的信號通道,但是我什么時候才能知道所有goroutines都完成了他們的工作,以便我可以發(fā)送信號進行進一步的計算?我甚至使用過WaitGroup,但這是在單個goroutine級別 - 我仍然無法知道所有goroutine何時完成了它的工作。SO中還有一個類似的問題沒有多大幫助:關閉未知長度的通道更新 :在代碼中,我將j循環(huán)值硬編碼為20 - 這正是我遇到問題的地方。我不知道在哪里循環(huán),如果我把它增加到50以上,接收被阻止。
1 回答

偶然的你
TA貢獻1841條經驗 獲得超3個贊
您錯誤地使用了等待組。
創(chuàng)建 goroutine 時,將其添加到等待組,并等待所有內容在單獨的 goroutine 中完成,然后關閉通道:
for j:=1;j<=totalPage;j++{
wg.Add(1)
go makePaginatedRequest(j, comment_title_chan, false)
}
go func() {
wg.Wait()
close(comment_title_chan)
}()
當 goroutine 返回時,將其標記為已完成:
func makePaginatedRequest(pageNo int, chunk chan CommentTitle, pilotMode bool) int{
defer wg.Done()
...
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消