2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
您的函數(shù)未同時(shí)處理節(jié)點(diǎn)的主要原因Dijkstra是您等待 goroutine 在循環(huán)內(nèi)完成(使用wg.Wait())。本質(zhì)上,每個(gè)節(jié)點(diǎn)不是同時(shí)處理的。
一種可能的解決方案:
首先,修改您的oneDijkstra函數(shù)以接收您將向其發(fā)送數(shù)據(jù)的通道(數(shù)據(jù)只是包含所有信息的結(jié)構(gòu))。
func ondeDijkstra(node int, wg *sync.WaitGroup, list []Edge, nodes []int, neighbours []Edge, dataCh chan<- data){
defer wg.Done()
//your calculations
// ...
datach <- data{node, routes, distances}
}
接下來(lái),在Dijkstra函數(shù)中,您需要更改一些內(nèi)容。
dataCh首先,啟動(dòng)一個(gè)從通道讀取并添加到地圖的 goroutine 。我個(gè)人更喜歡這種解決方案,因?yàn)樗梢员苊馔瑫r(shí)修改地圖。接下來(lái),遍歷節(jié)點(diǎn),為每個(gè)節(jié)點(diǎn)啟動(dòng)一個(gè) goroutine,并在循環(huán)后等待一切完成。
func Dijkstra(list []Edge, nodes []int) (map[int]map[int][]int, map[int]map[int]int) {
var wg sync.WaitGroup
datach := make(chan data)
done := make(chan bool)
dijk := make(map[int]map[int][]int)
distance := make(map[int]map[int]int)
neighbors := getAllNeighbors(list, nodes)
//start a goroutine that will read from the data channel
go func(){
for d := range dataCh {
dijk[d.node] = d.routes
distance[d.node] = d.distances
}
done <- true //this is used to wait until all data has been read from the channel
}()
wg.Add(len(nodes))
for _, node := range nodes {
go oneDijkstra(node, &wg, list, nodes, neighbors, dataCh)
}
wg.Wait()
close(dataCh) //this closes the dataCh channel, which will make the for-range loop exit once all the data has been read
<- done //we wait for all of the data to get read and put into maps
return dijk, distance
}

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
我認(rèn)為將您的等待移到 for 循環(huán)之后并將結(jié)果直接分配給您的切片將滿足您的需求。
for _, node := range nodes { //for every node we have we are going to get the shortest path to all the other nodes
wg.Add(1) //We add our next goroutine in the waitgroup
go func() { //goroutine
defer wg.Done();
dijk[node] , distance[node] = oneDijkstra(node, &wg, list, nodes, neighbors) //function that will give us the shortes path from the node to other nodes of the list
}()
}
wg.wait();
- 2 回答
- 0 關(guān)注
- 103 瀏覽
添加回答
舉報(bào)