2 回答

TA貢獻(xiàn)1847條經(jīng)驗 獲得超11個贊
您的函數(shù)未同時處理節(jié)點的主要原因Dijkstra是您等待 goroutine 在循環(huán)內(nèi)完成(使用wg.Wait())。本質(zhì)上,每個節(jié)點不是同時處理的。
一種可能的解決方案:
首先,修改您的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}
}
接下來,在Dijkstra函數(shù)中,您需要更改一些內(nèi)容。
dataCh首先,啟動一個從通道讀取并添加到地圖的 goroutine 。我個人更喜歡這種解決方案,因為它可以避免同時修改地圖。接下來,遍歷節(jié)點,為每個節(jié)點啟動一個 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)驗 獲得超3個贊
我認(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)注
- 97 瀏覽
添加回答
舉報