我在 Go 中解決了一個難題,它通過旋轉 ASCII 字節值以匹配行方式(左->右)或列方式(頂部->底部)的字符串,在 2D 字節數組中找到一個字符串。我能夠按順序解決它,當它同時解決它時,我嘗試啟動一個 go-routine 來處理特定的輸入組合,看看是否有任何可能的 25 個旋轉可以找到匹配項。代碼摘要如下該FindByConcurrentRot方法采用 2D 字符數組輸入并嘗試在各種可能的輸入組合中找到字符串的匹配項。問題是 - 下面使用的并發方法是否有效?如何改進?將順序例程“按原樣”轉換為并發程序的方法是否錯誤?即是否應該重寫整個程序以充分利用并發特性?// searchResult defines the information needed to pass to identify if a match has been identified during concurrent searchtype searchResult struct { row int col int rot int found bool}// processSearchResults runs the gorotuine to perform the search for a particular rotation of inputfunc processSearchResults(wg *sync.WaitGroup, iter int, resultChan chan searchResult, table [][]byte, word string) { // call goroutine end when the function returns defer wg.Done() if iter >= 1 { rotate(table, iter) } x, y, match := present(table, word) if match { resultChan <- searchResult{row: x, col: y, rot: iter, found: true} return } resultChan <- searchResult{found: false}}// doCopy creates a copy of the original table to passed for each iteration of the concurrent search// This is an EXPENSIVE operation on a goroutine, because of memory copy operations// The copy is needed for the goroutines to have their own control of data and not run into data// races by passing the original data to each of themfunc doCopy(table [][]byte) [][]byte { copyTable := make([][]byte, len(table)) for i := range table { copyTable[i] = make([]byte, len(table[i])) copy(copyTable[i], table[i]) } return copyTable}此 Go 操場鏈接上的完整 MVCE - https://go.dev/play/p/7YFAsAlFRUw
如何對多個 goroutine 共享的數據結構執行并發操作
慕田峪7331174
2022-11-08 16:55:48