1 回答

TA貢獻2012條經(jīng)驗 獲得超12個贊
您在切片上存在數(shù)據(jù)競爭queue。并發(fā) goroutines,當通過sync.Mutex鎖以受控方式從隊列頭部彈出元素時?;蛘呤褂靡粋€通道來管理工作項的“隊列”。
要將您所擁有的轉(zhuǎn)換為使用通道,請更新工作人員以將輸入通道作為您的隊列 - 并在通道上進行范圍,以便每個工作人員可以處理多個任務(wù):
func consumer_task(task_num int, ch <-chan string) {
fmt.Printf("I'm consumer task #%v\n", task_num)
for item := range ch {
fmt.Printf("task %d consuming: Line item: %v\n", task_num, item)
}
// each worker will drop out of their loop when channel is closed
}
從切片更改queue為頻道和 feed 項目,如下所示:
queue := make(chan string)
go func() {
// Loop through each line in the file and append it to the queue
for scanner.Scan() {
queue <- scanner.Text()
}
close(queue) // signal to workers that there is no more items
}()
然后只需更新您的工作調(diào)度程序代碼以添加頻道輸入:
go func(i int) {
consumer_task(i, queue) // add the queue parameter
wg.Done()
}(i)
https://go.dev/play/p/AzHyztipUZI
- 1 回答
- 0 關(guān)注
- 98 瀏覽
添加回答
舉報